diff --git a/Yubico.YubiKey/examples/Fido2SampleCode/Run/Fido2SampleRun.Operations.cs b/Yubico.YubiKey/examples/Fido2SampleCode/Run/Fido2SampleRun.Operations.cs index d20e2ce12..0a2db773d 100644 --- a/Yubico.YubiKey/examples/Fido2SampleCode/Run/Fido2SampleRun.Operations.cs +++ b/Yubico.YubiKey/examples/Fido2SampleCode/Run/Fido2SampleRun.Operations.cs @@ -364,25 +364,22 @@ public bool RunGetAssertions() var salt = ReadOnlyMemory.Empty; bool isValid = Fido2Protocol.RunGetAuthenticatorInfo(_yubiKeyChosen, out var authenticatorInfo); - if (isValid) + if (isValid && authenticatorInfo.Extensions.Contains("hmac-secret")) { - if (authenticatorInfo.Extensions.Contains("hmac-secret")) - { - SampleMenu.WriteMessage( - MessageType.Title, 0, - "\nWould you like the hmac-secret returned with the assertions?\n" + - "If not, type Enter.\n" + - "Otherwise, enter a string that will be used to derive a salt.\n" + - "Normally, a salt is 32 random bytes or the digest of some identifying data.\n" + - "This sample code will perform SHA-256 on the input you provide and send that\n" + - "digest to the YubiKey as the salt.\n"); - _ = SampleMenu.ReadResponse(out string dataToDigest); - byte[] dataBytes = System.Text.Encoding.Unicode.GetBytes(dataToDigest); - var digester = CryptographyProviders.Sha256Creator(); - _ = digester.TransformFinalBlock(dataBytes, 0, dataBytes.Length); - - salt = new ReadOnlyMemory(digester.Hash); - } + SampleMenu.WriteMessage( + MessageType.Title, 0, + "\nWould you like the hmac-secret returned with the assertions?\n" + + "If not, type Enter.\n" + + "Otherwise, enter a string that will be used to derive a salt.\n" + + "Normally, a salt is 32 random bytes or the digest of some identifying data.\n" + + "This sample code will perform SHA-256 on the input you provide and send that\n" + + "digest to the YubiKey as the salt.\n"); + _ = SampleMenu.ReadResponse(out string dataToDigest); + byte[] dataBytes = System.Text.Encoding.Unicode.GetBytes(dataToDigest); + var digester = CryptographyProviders.Sha256Creator(); + _ = digester.TransformFinalBlock(dataBytes, 0, dataBytes.Length); + + salt = new ReadOnlyMemory(digester.Hash); } _keyCollector.Operation = Fido2KeyCollectorOperation.GetAssertion; diff --git a/Yubico.YubiKey/examples/Fido2SampleCode/Run/Fido2SampleRun.cs b/Yubico.YubiKey/examples/Fido2SampleCode/Run/Fido2SampleRun.cs index 864677592..008f743c8 100644 --- a/Yubico.YubiKey/examples/Fido2SampleCode/Run/Fido2SampleRun.cs +++ b/Yubico.YubiKey/examples/Fido2SampleCode/Run/Fido2SampleRun.cs @@ -84,12 +84,9 @@ public void RunSample(bool displayGuiMessage = true) // inserted. If so, keep using it. If not, find another default. // does not require a chosen YubiKey, this method will do nothing // and return true. - if (DefaultChooseYubiKey(menuItem)) + if (DefaultChooseYubiKey(menuItem) && !RunMenuItem(menuItem)) { - if (!RunMenuItem(menuItem)) - { - menuItem = Fido2MainMenuItem.Exit; - } + menuItem = Fido2MainMenuItem.Exit; } } while (menuItem != Fido2MainMenuItem.Exit); diff --git a/Yubico.YubiKey/examples/PivSampleCode/Converters/DsaSignatureConverter.cs b/Yubico.YubiKey/examples/PivSampleCode/Converters/DsaSignatureConverter.cs index 9a7a8255a..7b0071baf 100644 --- a/Yubico.YubiKey/examples/PivSampleCode/Converters/DsaSignatureConverter.cs +++ b/Yubico.YubiKey/examples/PivSampleCode/Converters/DsaSignatureConverter.cs @@ -83,33 +83,29 @@ public static byte[] GetNonStandardDsaFromStandard(byte[] signature, KeyType alg int offsetR = 0; int offsetS = 0; bool isValid = false; - if (tlvReader.TryReadNestedTlv(out var seqReader, 0x30)) + if (tlvReader.TryReadNestedTlv(out var seqReader, 0x30) && + seqReader.TryReadValue(out rValue, 0x02) && + seqReader.TryReadValue(out sValue, 0x02)) { - if (seqReader.TryReadValue(out rValue, 0x02)) + // Skip any leading 00 bytes. + while (rValue.Span[offsetR] == 0) { - if (seqReader.TryReadValue(out sValue, 0x02)) + offsetR++; + if (offsetR == rValue.Length - 1) { - // Skip any leading 00 bytes. - while (rValue.Span[offsetR] == 0) - { - offsetR++; - if (offsetR == rValue.Length - 1) - { - break; - } - } - while (sValue.Span[offsetS] == 0) - { - offsetS++; - if (offsetS == sValue.Length - 1) - { - break; - } - } - - isValid = rValue.Length - offsetR <= elementLength && sValue.Length - offsetS <= elementLength; + break; } } + while (sValue.Span[offsetS] == 0) + { + offsetS++; + if (offsetS == sValue.Length - 1) + { + break; + } + } + + isValid = rValue.Length - offsetR <= elementLength && sValue.Length - offsetS <= elementLength; } if (isValid) diff --git a/Yubico.YubiKey/examples/PivSampleCode/Converters/PemOperations.cs b/Yubico.YubiKey/examples/PivSampleCode/Converters/PemOperations.cs index a9bd99091..4d672f224 100644 --- a/Yubico.YubiKey/examples/PivSampleCode/Converters/PemOperations.cs +++ b/Yubico.YubiKey/examples/PivSampleCode/Converters/PemOperations.cs @@ -185,12 +185,10 @@ private static bool VerifyPemHeaderAndFooter(char[] pemKeyString, string title) char[] targetStart = (Part1 + title + Part2And4).ToCharArray(); char[] targetEnd = (Part3 + title + Part2And4).ToCharArray(); bool returnValue = false; - if (pemKeyString.Length > targetStart.Length + targetEnd.Length) + if (pemKeyString.Length > targetStart.Length + targetEnd.Length && + CompareToTarget(pemKeyString, 0, targetStart)) { - if (CompareToTarget(pemKeyString, 0, targetStart)) - { - returnValue = CompareToTarget(pemKeyString, pemKeyString.Length - targetEnd.Length, targetEnd); - } + returnValue = CompareToTarget(pemKeyString, pemKeyString.Length - targetEnd.Length, targetEnd); } return returnValue; diff --git a/Yubico.YubiKey/examples/PivSampleCode/Converters/SignatureAlgIdConverter.cs b/Yubico.YubiKey/examples/PivSampleCode/Converters/SignatureAlgIdConverter.cs index 99ce8e975..65c61fb04 100644 --- a/Yubico.YubiKey/examples/PivSampleCode/Converters/SignatureAlgIdConverter.cs +++ b/Yubico.YubiKey/examples/PivSampleCode/Converters/SignatureAlgIdConverter.cs @@ -262,25 +262,19 @@ private bool SetFromOid(ReadOnlyMemory oid) // Then verify the len(y) is supported. private void ReadPssParams(ReadOnlyMemory algIdParams) { - if (algIdParams.Length == 2) + if (algIdParams.Length == 2 && algIdParams.Span[0] == 0x30 && algIdParams.Span[1] == 0) { - if (algIdParams.Span[0] == 0x30 && algIdParams.Span[1] == 0) - { - PssSaltLength = 20; - } + PssSaltLength = 20; } - else if (algIdParams.Length == 50) + else if (algIdParams.Length == 50 && algIdParams.Span[16] == algIdParams.Span[44]) { - if (algIdParams.Span[16] == algIdParams.Span[44]) + PssSaltLength = algIdParams.Span[16] switch { - PssSaltLength = algIdParams.Span[16] switch - { - 1 => 32, - 2 => 48, - 3 => 64, - _ => 0, - }; - } + 1 => 32, + 2 => 48, + 3 => 64, + _ => 0, + }; } switch (PssSaltLength) diff --git a/Yubico.YubiKey/examples/PivSampleCode/Run/PivSampleRun.cs b/Yubico.YubiKey/examples/PivSampleCode/Run/PivSampleRun.cs index 395050901..b08dc8b3b 100644 --- a/Yubico.YubiKey/examples/PivSampleCode/Run/PivSampleRun.cs +++ b/Yubico.YubiKey/examples/PivSampleCode/Run/PivSampleRun.cs @@ -82,12 +82,9 @@ public void RunSample() // inserted. If so, keep using it. If not, find another default. // does not require a chosen YubiKey, this method will do nothing // and return true. - if (DefaultChooseYubiKey(menuItem)) + if (DefaultChooseYubiKey(menuItem) && !RunMenuItem(menuItem)) { - if (!RunMenuItem(menuItem)) - { - menuItem = PivMainMenuItem.Exit; - } + menuItem = PivMainMenuItem.Exit; } } while (menuItem != PivMainMenuItem.Exit); diff --git a/Yubico.YubiKey/examples/U2fSampleCode/Run/U2fSampleRun.cs b/Yubico.YubiKey/examples/U2fSampleCode/Run/U2fSampleRun.cs index 5fab8045d..d32d0fffb 100644 --- a/Yubico.YubiKey/examples/U2fSampleCode/Run/U2fSampleRun.cs +++ b/Yubico.YubiKey/examples/U2fSampleCode/Run/U2fSampleRun.cs @@ -70,12 +70,9 @@ public void RunSample() // inserted. If so, keep using it. If not, find another default. // does not require a chosen YubiKey, this method will do nothing // and return true. - if (DefaultChooseYubiKey(menuItem)) + if (DefaultChooseYubiKey(menuItem) && !RunMenuItem(menuItem)) { - if (!RunMenuItem(menuItem)) - { - menuItem = U2fMainMenuItem.Exit; - } + menuItem = U2fMainMenuItem.Exit; } } while (menuItem != U2fMainMenuItem.Exit); diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/EnumerateRpsBeginResponse.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/EnumerateRpsBeginResponse.cs index 9114ba939..174019e86 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/EnumerateRpsBeginResponse.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/EnumerateRpsBeginResponse.cs @@ -72,14 +72,12 @@ public EnumerateRpsBeginResponse(ResponseApdu responseApdu) { var credentialManagementData = _response.GetData(); - if (credentialManagementData.RelyingParty is not null - && credentialManagementData.RelyingPartyIdHash is not null - && credentialManagementData.TotalRelyingPartyCount is not null) + if (credentialManagementData.RelyingParty is not null && + credentialManagementData.RelyingPartyIdHash is not null && + credentialManagementData.TotalRelyingPartyCount is not null && + credentialManagementData.RelyingParty.IsMatchingRelyingPartyId(credentialManagementData.RelyingPartyIdHash.Value)) { - if (credentialManagementData.RelyingParty.IsMatchingRelyingPartyId(credentialManagementData.RelyingPartyIdHash.Value)) - { - return (credentialManagementData.TotalRelyingPartyCount.Value, credentialManagementData.RelyingParty); - } + return (credentialManagementData.TotalRelyingPartyCount.Value, credentialManagementData.RelyingParty); } throw new Ctap2DataException(ExceptionMessages.InvalidFido2Info); diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/EnumerateRpsGetNextResponse.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/EnumerateRpsGetNextResponse.cs index aeacbf512..62da118a2 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/EnumerateRpsGetNextResponse.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/EnumerateRpsGetNextResponse.cs @@ -43,13 +43,12 @@ public EnumerateRpsGetNextResponse(ResponseApdu responseApdu) public RelyingParty GetData() { var credentialManagementData = _response.GetData(); - if (!(credentialManagementData.RelyingParty is null) && - !(credentialManagementData.RelyingPartyIdHash is null)) + + if (credentialManagementData.RelyingParty is not null && + credentialManagementData.RelyingPartyIdHash is not null && + credentialManagementData.RelyingParty.IsMatchingRelyingPartyId(credentialManagementData.RelyingPartyIdHash.Value)) { - if (credentialManagementData.RelyingParty.IsMatchingRelyingPartyId(credentialManagementData.RelyingPartyIdHash.Value)) - { - return credentialManagementData.RelyingParty; - } + return credentialManagementData.RelyingParty; } throw new Ctap2DataException(ExceptionMessages.InvalidFido2Info); diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Management/Commands/SetDeviceInfoBaseCommand.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Management/Commands/SetDeviceInfoBaseCommand.cs index 81de123d0..c182d6b8e 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Management/Commands/SetDeviceInfoBaseCommand.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Management/Commands/SetDeviceInfoBaseCommand.cs @@ -67,12 +67,9 @@ public int? AutoEjectTimeout set { - if (value.HasValue) + if (value.HasValue && (value < ushort.MinValue || value > ushort.MaxValue)) { - if (value < ushort.MinValue || value > ushort.MaxValue) - { - throw new ArgumentOutOfRangeException(nameof(value)); - } + throw new ArgumentOutOfRangeException(nameof(value)); } _autoEjectTimeout = (ushort?)value; diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Oath/OathSession.Password.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Oath/OathSession.Password.cs index ea07f470c..53d9dbdf3 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Oath/OathSession.Password.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Oath/OathSession.Password.cs @@ -314,12 +314,9 @@ public void SetPassword() /// public bool TrySetPassword(ReadOnlyMemory currentPassword, ReadOnlyMemory newPassword) { - if (IsPasswordProtected || !currentPassword.IsEmpty) + if ((IsPasswordProtected || !currentPassword.IsEmpty) && !TryVerifyPassword(currentPassword)) { - if (!TryVerifyPassword(currentPassword)) - { - return false; - } + return false; } var setPasswordResponse = Connection.SendCommand(new SetPasswordCommand(newPassword, _oathData)); diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Pipelines/Scp03ApduTransform.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Pipelines/Scp03ApduTransform.cs index 9b4e2f800..bb11b0a40 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Pipelines/Scp03ApduTransform.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Pipelines/Scp03ApduTransform.cs @@ -146,15 +146,12 @@ public void Dispose() // disposed. protected virtual void Dispose(bool disposing) { - if (!_disposed) + if (!_disposed && disposing) { - if (disposing) - { - Scp03Keys.Dispose(); - _session.Dispose(); - - _disposed = true; - } + Scp03Keys.Dispose(); + _session.Dispose(); + + _disposed = true; } } } diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/CompleteAuthenticateManagementKeyResponse.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/CompleteAuthenticateManagementKeyResponse.cs index 87aa40094..e2bdcd43c 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/CompleteAuthenticateManagementKeyResponse.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/CompleteAuthenticateManagementKeyResponse.cs @@ -150,14 +150,12 @@ public AuthenticateManagementKeyResult GetData() // means the OffCard authenticated. If the expected response // is correct, change it to fully authenticated. var tlvReader = new TlvReader(ResponseApdu.Data); - if (tlvReader.TryReadNestedTlv(out tlvReader, EncodingTag)) + if (tlvReader.TryReadNestedTlv(out var seqReader, EncodingTag) && + seqReader.TryReadValue(out var tlvBytes, ResponseTag)) { - if (tlvReader.TryReadValue(out var tlvBytes, ResponseTag)) - { - return tlvBytes.Span.SequenceEqual(YubiKeyAuthenticationExpectedResponse.Span) - ? AuthenticateManagementKeyResult.MutualFullyAuthenticated - : AuthenticateManagementKeyResult.MutualYubiKeyAuthenticationFailed; - } + return tlvBytes.Span.SequenceEqual(YubiKeyAuthenticationExpectedResponse.Span) + ? AuthenticateManagementKeyResult.MutualFullyAuthenticated + : AuthenticateManagementKeyResult.MutualYubiKeyAuthenticationFailed; } throw new MalformedYubiKeyResponseException( diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/GetDataCommand.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/GetDataCommand.cs index 63d993ead..906987fc0 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/GetDataCommand.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/GetDataCommand.cs @@ -145,16 +145,15 @@ public int DataTag get => _tag; set { - if (value < MinimumVendorTag || value > MaximumVendorTag) + if ((value < MinimumVendorTag || value > MaximumVendorTag) && + value != DiscoveryTag && + value != BiometricGroupTemplateTag) { - if (value != DiscoveryTag && value != BiometricGroupTemplateTag) - { - throw new ArgumentException( - string.Format( - CultureInfo.CurrentCulture, - ExceptionMessages.InvalidDataTag, - value)); - } + throw new ArgumentException( + string.Format( + CultureInfo.CurrentCulture, + ExceptionMessages.InvalidDataTag, + value)); } _tag = value; } diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/PutDataCommand.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/PutDataCommand.cs index b07b5a07b..d20b794fa 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/PutDataCommand.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/PutDataCommand.cs @@ -215,16 +215,13 @@ public int DataTag get => _tag; set { - if (value < MinimumVendorTag || value > MaximumVendorTag) + if ((value < MinimumVendorTag || value > MaximumVendorTag) && value != BiometricGroupTemplateTag) { - if (value != BiometricGroupTemplateTag) - { - throw new ArgumentException( - string.Format( - CultureInfo.CurrentCulture, - ExceptionMessages.InvalidDataTag, - value)); - } + throw new ArgumentException( + string.Format( + CultureInfo.CurrentCulture, + ExceptionMessages.InvalidDataTag, + value)); } _tag = value; } @@ -456,21 +453,20 @@ private byte[] BuildPutDataApduData() // 53 03 01 02 03 04 private static bool IsDataEncoded(ReadOnlyMemory encoding) { - if (encoding.Length != 0) + if (encoding.Length == 0) { - var tlvReader = new TlvReader(encoding); - if (tlvReader.PeekTag() == PivPutDataTag) - { - if (tlvReader.TryReadValue(out _, PivPutDataTag)) - { - if (!tlvReader.HasData) - { - return true; - } - } - } + return false; } + var tlvReader = new TlvReader(encoding); + + if (tlvReader.PeekTag() == PivPutDataTag && + tlvReader.TryReadValue(out _, PivPutDataTag) && + !tlvReader.HasData) + { + return true; + } + return false; } diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Objects/CardCapabilityContainer.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Objects/CardCapabilityContainer.cs index fa9c31a83..7fb15317b 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Objects/CardCapabilityContainer.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Objects/CardCapabilityContainer.cs @@ -349,19 +349,19 @@ public override bool TryDecode(ReadOnlyMemory encodedData) // return false. private bool TryReadUniqueId(bool isValid, TlvReader tlvReader) { - if (isValid) + if (!isValid) { - _log.LogInformation("Decode data into CardCapabilityContainer: UniqueId."); - if (tlvReader.TryReadValue(out var encodedUniqueId, UniqueCardIdTag)) - { - if (encodedUniqueId.Length == UniqueCardIdLength && - MemoryExtensions.SequenceEqual(encodedUniqueId.Slice(AidOffset, AidLength).Span, ApplicationIdentifier.Span)) - { - var dest = new Memory(_uniqueCardIdentifier); - encodedUniqueId.CopyTo(dest); - return true; - } - } + return false; + } + + _log.LogInformation("Decode data into CardCapabilityContainer: UniqueId."); + if (tlvReader.TryReadValue(out var encodedUniqueId, UniqueCardIdTag) && + encodedUniqueId.Length == UniqueCardIdLength && + MemoryExtensions.SequenceEqual(encodedUniqueId.Slice(AidOffset, AidLength).Span, ApplicationIdentifier.Span)) + { + var dest = new Memory(_uniqueCardIdentifier); + encodedUniqueId.CopyTo(dest); + return true; } return false; diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Objects/CardholderUniqueId.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Objects/CardholderUniqueId.cs index 4c000233e..6d43c95b6 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Objects/CardholderUniqueId.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Objects/CardholderUniqueId.cs @@ -276,18 +276,18 @@ public override bool TryDecode(ReadOnlyMemory encodedData) // return false. private bool TryReadFascNumber(bool isValid, TlvReader tlvReader) { - if (isValid) + if (!isValid) { - _log.LogInformation("Decode data into CardholderUniqueId: FascNumber."); - if (tlvReader.TryReadValue(out var encodedFascn, FascNumberTag)) - { - if (MemoryExtensions.SequenceEqual(encodedFascn.Span, FascNumber.Span)) - { - var dest = new Memory(_fascNumber); - encodedFascn.CopyTo(dest); - return true; - } - } + return false; + } + + _log.LogInformation("Decode data into CardholderUniqueId: FascNumber."); + if (tlvReader.TryReadValue(out var encodedFascn, FascNumberTag) && + MemoryExtensions.SequenceEqual(encodedFascn.Span, FascNumber.Span)) + { + var dest = new Memory(_fascNumber); + encodedFascn.CopyTo(dest); + return true; } return false; @@ -300,18 +300,18 @@ private bool TryReadFascNumber(bool isValid, TlvReader tlvReader) // return false. private bool TryReadGuid(bool isValid, TlvReader tlvReader) { - if (isValid) + if (!isValid) { - _log.LogInformation("Decode data into CardholderUniqueId: Guid."); - if (tlvReader.TryReadValue(out var encodedGuidBytes, GuidTag)) - { - if (encodedGuidBytes.Length == GuidLength) - { - var dest = new Memory(_guidValue); - encodedGuidBytes.CopyTo(dest); - return true; - } - } + return false; + } + + _log.LogInformation("Decode data into CardholderUniqueId: Guid."); + if (tlvReader.TryReadValue(out var encodedGuidBytes, GuidTag) && + encodedGuidBytes.Length == GuidLength) + { + var dest = new Memory(_guidValue); + encodedGuidBytes.CopyTo(dest); + return true; } return false; @@ -319,17 +319,17 @@ private bool TryReadGuid(bool isValid, TlvReader tlvReader) private bool TryReadExpirationDate(bool isValid, TlvReader tlvReader) { - if (isValid) + if (!isValid) { - _log.LogInformation("Decode data into CardholderUniqueId: ExpirationDate."); - if (tlvReader.TryReadString(out string theDate, ExpirationDateTag, System.Text.Encoding.ASCII)) - { - if (theDate.Equals(FixedDate, StringComparison.Ordinal)) - { - ExpirationDate = new DateTime(FixedDateYear, FixedDateMonth, FixedDateDay); - return true; - } - } + return false; + } + + _log.LogInformation("Decode data into CardholderUniqueId: ExpirationDate."); + if (tlvReader.TryReadString(out string theDate, ExpirationDateTag, System.Text.Encoding.ASCII) && + theDate.Equals(FixedDate, StringComparison.Ordinal)) + { + ExpirationDate = new DateTime(FixedDateYear, FixedDateMonth, FixedDateDay); + return true; } return false; @@ -337,19 +337,19 @@ private bool TryReadExpirationDate(bool isValid, TlvReader tlvReader) private bool TryReadTrailingElements(bool isValid, TlvReader tlvReader) { - if (isValid) + if (!isValid) { - _log.LogInformation("Decode data into CardholderUniqueId: TrailingElements."); - if (tlvReader.TryReadValue(out var signatureBytes, SignatureTag)) - { - if (signatureBytes.Length == 0 && tlvReader.TryReadValue(out var lrc, LrcTag)) - { - if (lrc.Length == 0 && !tlvReader.HasData) - { - return true; - } - } - } + return false; + } + + _log.LogInformation("Decode data into CardholderUniqueId: TrailingElements."); + if (tlvReader.TryReadValue(out var signatureBytes, SignatureTag) && + signatureBytes.Length == 0 && + tlvReader.TryReadValue(out var lrc, LrcTag) && + lrc.Length == 0 && + !tlvReader.HasData) + { + return true; } return false; diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Objects/PivDataObject.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Objects/PivDataObject.cs index fa12e533a..0434f4d96 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Objects/PivDataObject.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Objects/PivDataObject.cs @@ -152,14 +152,13 @@ public int DataTag /// protected virtual bool IsValidAlternateTag(int dataTag) { - if (dataTag != GetDefinedDataTag()) + if (dataTag != GetDefinedDataTag() && + (dataTag < MinVendorDataTag || + dataTag > MaxVendorDataTag || + (dataTag >= MinPivDataTag && dataTag <= MaxPivDataTag) || + (dataTag >= MinYubicoDataTag && dataTag <= MaxYubicoDataTag))) { - if (dataTag < MinVendorDataTag || dataTag > MaxVendorDataTag - || (dataTag >= MinPivDataTag && dataTag <= MaxPivDataTag) - || (dataTag >= MinYubicoDataTag && dataTag <= MaxYubicoDataTag)) - { - return false; - } + return false; } return true; diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.Pin.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.Pin.cs index f79b7a764..861a934a6 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.Pin.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.Pin.cs @@ -541,27 +541,31 @@ public bool TryChangePinAndPukRetryCounts(ReadOnlyMemory managementKey, // It will also return true if the mode is None (YubiKey is not // Pin-derived), in which case neither the PIN nor mgmt key is // verified/authenticated. - if (TryGetChangePinMode(pin, out var mode, out retriesRemaining)) + if (!TryGetChangePinMode(pin, out var mode, out retriesRemaining)) { - if (ManagementKeyAuthenticated || TryAuthenticateManagementKey(managementKey, true)) - { - if (PinVerified || TryVerifyPin(pin, out retriesRemaining)) - { - var setRetriesResponse = Connection.SendCommand(setRetriesCommand); - if (setRetriesResponse.Status == ResponseStatus.Success) - { - if (mode != PivPinOnlyMode.None) - { - // By passing Empty, this method will use the default PIN. - SetPinOnlyMode(ReadOnlyMemory.Empty, mode, out _); - } + return false; + } - UpdateAdminData(); + if (!ManagementKeyAuthenticated && !TryAuthenticateManagementKey(managementKey, true)) + { + return false; + } - return true; - } - } + if (!PinVerified && !TryVerifyPin(pin, out retriesRemaining)) + { + return false; + } + + var setRetriesResponse = Connection.SendCommand(setRetriesCommand); + if (setRetriesResponse.Status == ResponseStatus.Success) + { + if (mode != PivPinOnlyMode.None) + { + // By passing Empty, this method will use the default PIN. + SetPinOnlyMode(ReadOnlyMemory.Empty, mode, out _); } + UpdateAdminData(); + return true; } return false; diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.Pinonly.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.Pinonly.cs index 8a5a53702..97d84bd79 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.Pinonly.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.Pinonly.cs @@ -471,41 +471,41 @@ private PivPinOnlyMode GetPinDerivedStatus( return PivPinOnlyMode.None; } - if (response.Status == ResponseStatus.Success) + if (response.Status != ResponseStatus.Success) + { + return PivPinOnlyMode.PinDerivedUnavailable; + } + if (!adminData.TryDecode(response.GetData())) + { + return PivPinOnlyMode.PinDerivedUnavailable; + } + if (adminData.Salt is null) + { + return PivPinOnlyMode.None; + } + + // If we have already collected the PIN, this call will do + // nothing (it won't collect it again). + specialKeyCollector.VerifyPinAndSave(this, userKeyCollector); + // If we're already PIN-protected, then the current mgmt key + // is the PIN-protected value. So put the derived key into + // the new buffer and compare. + // If not, put it into the current buffer and authenticate. + _ = specialKeyCollector.DeriveKeyData( + (ReadOnlyMemory)adminData.Salt, ManagementKeyAlgorithm, isPinProtected); + if (isPinProtected) { - if (adminData.TryDecode(response.GetData())) + if (specialKeyCollector.GetCurrentMgmtKey().Span + .SequenceEqual(specialKeyCollector.GetNewMgmtKey().Span)) { - if (adminData.Salt is null) - { - return PivPinOnlyMode.None; - } - - // If we have already collected the PIN, this call will do - // nothing (it won't collect it again). - specialKeyCollector.VerifyPinAndSave(this, userKeyCollector); - - // If we're already PIN-protected, then the current mgmt key - // is the PIN-protected value. So put the derived key into - // the new buffer and compare. - // If not, put it into the current buffer and authenticate. - _ = specialKeyCollector.DeriveKeyData( - (ReadOnlyMemory)adminData.Salt, ManagementKeyAlgorithm, isPinProtected); - - if (isPinProtected) - { - if (specialKeyCollector.GetCurrentMgmtKey().Span - .SequenceEqual(specialKeyCollector.GetNewMgmtKey().Span)) - { - return PivPinOnlyMode.PinDerived; - } - } - else - { - if (TryAuthenticateWithKeyCollector(true)) - { - return PivPinOnlyMode.PinDerived; - } - } + return PivPinOnlyMode.PinDerived; + } + } + else + { + if (TryAuthenticateWithKeyCollector(true)) + { + return PivPinOnlyMode.PinDerived; } } @@ -1379,16 +1379,18 @@ public void PerformKeyDerive(ReadOnlyMemory pin, byte[] saltData, PivAlgor // If not 3DES, it is not weak. public bool IsKeyDataWeak(PivAlgorithm algorithm) { - if (algorithm == PivAlgorithm.TripleDes) + if (algorithm != PivAlgorithm.TripleDes) { - if (_keyData.Span.Slice(start: 0, length: 8).SequenceEqual(_keyData.Span.Slice(start: 8, length: 8)) - || _keyData.Span.Slice(start: 8, length: 8) - .SequenceEqual(_keyData.Span.Slice(start: 16, length: 8))) - { - return true; - } + return false; } + if (_keyData.Span.Slice(start: 0, length: 8).SequenceEqual(_keyData.Span.Slice(start: 8, length: 8)) + || _keyData.Span.Slice(start: 8, length: 8) + .SequenceEqual(_keyData.Span.Slice(start: 16, length: 8))) + { + return true; + } + return false; } } diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Scp/ScpConnection.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Scp/ScpConnection.cs index e51ea8318..2d6809b79 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Scp/ScpConnection.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Scp/ScpConnection.cs @@ -73,15 +73,12 @@ private ScpApduTransform CreateScpPipeline(ScpKeyParameters keyParameters) protected override void Dispose(bool disposing) { - if (!_disposed) + if (!_disposed && disposing) { - if (disposing) - { - _scpApduTransform.Dispose(); - _disposed = true; - } + _scpApduTransform.Dispose(); + _disposed = true; } - + base.Dispose(disposing); } } diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Scp03/Scp03Connection.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Scp03/Scp03Connection.cs index a12d7aede..aadcb32de 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Scp03/Scp03Connection.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Scp03/Scp03Connection.cs @@ -83,15 +83,12 @@ private Scp03ApduTransform SetObject( protected override void Dispose(bool disposing) { - if (!_disposed) + if (!_disposed && disposing) { - if (disposing) - { - _scp03ApduTransform.Dispose(); - _disposed = true; - } + _scp03ApduTransform.Dispose(); + _disposed = true; } - + base.Dispose(disposing); } } diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Scp03/Session.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Scp03/Session.cs index e6f0cf854..26ccf9e3b 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Scp03/Session.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Scp03/Session.cs @@ -254,14 +254,10 @@ public void Dispose() protected virtual void Dispose(bool disposing) { - if (!_disposed) + if (!_disposed && disposing) { - if (disposing) - { - _sessionKeys?.Dispose(); - - _disposed = true; - } + _sessionKeys?.Dispose(); + _disposed = true; } } } diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Scp03/SessionKeys.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Scp03/SessionKeys.cs index 63dc31dc7..8c997190f 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Scp03/SessionKeys.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Scp03/SessionKeys.cs @@ -56,16 +56,13 @@ public void Dispose() // Overwrite the memory of the keys protected virtual void Dispose(bool disposing) { - if (!_disposed) + if (!_disposed && disposing) { - if (disposing) - { - CryptographicOperations.ZeroMemory(_sessionMacKey.AsSpan()); - CryptographicOperations.ZeroMemory(_sessionEncryptionKey.AsSpan()); - CryptographicOperations.ZeroMemory(_sessionRmacKey.AsSpan()); - - _disposed = true; - } + CryptographicOperations.ZeroMemory(_sessionMacKey.AsSpan()); + CryptographicOperations.ZeroMemory(_sessionEncryptionKey.AsSpan()); + CryptographicOperations.ZeroMemory(_sessionRmacKey.AsSpan()); + + _disposed = true; } } } diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Scp03/StaticKeys.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Scp03/StaticKeys.cs index afddd42ad..f29b40178 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Scp03/StaticKeys.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Scp03/StaticKeys.cs @@ -228,16 +228,13 @@ public void Dispose() /// protected virtual void Dispose(bool disposing) { - if (!_disposed) + if (!_disposed && disposing) { - if (disposing) - { - CryptographicOperations.ZeroMemory(_macKey.AsSpan()); - CryptographicOperations.ZeroMemory(_encKey.AsSpan()); - CryptographicOperations.ZeroMemory(_dekKey.AsSpan()); - - _disposed = true; - } + CryptographicOperations.ZeroMemory(_macKey.AsSpan()); + CryptographicOperations.ZeroMemory(_encKey.AsSpan()); + CryptographicOperations.ZeroMemory(_dekKey.AsSpan()); + + _disposed = true; } } } diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/TouchFingerprintTask.cs b/Yubico.YubiKey/src/Yubico/YubiKey/TouchFingerprintTask.cs index 2dbb54b2f..3830ce9b6 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/TouchFingerprintTask.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/TouchFingerprintTask.cs @@ -111,12 +111,9 @@ public TouchFingerprintTask( _notifyTask = new Task(() => RunKeyCollectorTask(keyCollector)); _ = _notifyTask.ContinueWith((t) => HandleTaskException(t), TaskScheduler.Current); - if (connection is ICancelConnection cancelConnection) + if (connection is ICancelConnection cancelConnection && cancelConnection.LoadQueryCancel(IsCanceled)) { - if (cancelConnection.LoadQueryCancel(IsCanceled)) - { - _connection = cancelConnection; - } + _connection = cancelConnection; } if (_connection is null) diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/U2f/RegistrationData.cs b/Yubico.YubiKey/src/Yubico/YubiKey/U2f/RegistrationData.cs index 583e5742e..7a50cd8c2 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/U2f/RegistrationData.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/U2f/RegistrationData.cs @@ -136,20 +136,32 @@ public RegistrationData(ReadOnlyMemory encodedResponse) _log.LogInformation("Create a new instance of U2F RegistrationData by decoding."); bool isValid = false; int certLength = 1; - if (encodedResponse.Length > MinEncodedLength) + + if (encodedResponse.Length <= MinEncodedLength) + { + throw new ArgumentException( + string.Format( + CultureInfo.CurrentCulture, + ExceptionMessages.InvalidDataEncoding)); + } + + if (encodedResponse.Span[MsgReservedOffset] != MsgReservedValue || + encodedResponse.Span[MsgKeyHandleOffset] != KeyHandleLength || + encodedResponse.Span[MsgPublicKeyOffset] != PublicKeyTag) + { + throw new ArgumentException( + string.Format( + CultureInfo.CurrentCulture, + ExceptionMessages.InvalidDataEncoding)); + } + + var certAndSignatureBytes = encodedResponse.Slice(MsgCertOffset); + var tlvReader = new TlvReader(certAndSignatureBytes); + + if (tlvReader.TryReadEncoded(out var cert, CertTag)) { - if (encodedResponse.Span[MsgReservedOffset] == MsgReservedValue && - encodedResponse.Span[MsgKeyHandleOffset] == KeyHandleLength && - encodedResponse.Span[MsgPublicKeyOffset] == PublicKeyTag) - { - var certAndSignatureBytes = encodedResponse.Slice(MsgCertOffset); - var tlvReader = new TlvReader(certAndSignatureBytes); - if (tlvReader.TryReadEncoded(out var cert, CertTag)) - { - certLength = cert.Length; - isValid = true; - } - } + certLength = cert.Length; + isValid = true; } if (!isValid) diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/BioEnrollTests.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/BioEnrollTests.cs index 1ccc8f068..db25a60ab 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/BioEnrollTests.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/BioEnrollTests.cs @@ -138,12 +138,11 @@ private bool LocalKeyCollector(KeyEntryData arg) { bool callCancel = _callCancelCount == 0 ? false : true; - if (_callCancelCount > 0 && !(arg.LastBioEnrollSampleResult is null)) + if (_callCancelCount > 0 && + arg.LastBioEnrollSampleResult is not null && + arg.LastBioEnrollSampleResult.RemainingSampleCount != _callCancelCount) { - if (arg.LastBioEnrollSampleResult.RemainingSampleCount != _callCancelCount) - { - callCancel = false; - } + callCancel = false; } switch (arg.Request) diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/X500NameBuilder.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/X500NameBuilder.cs index f8ebb2251..a9177903a 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/X500NameBuilder.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/X500NameBuilder.cs @@ -102,13 +102,11 @@ public byte[] GetEncodedName() { foreach (X500NameElement? nameElement in enumValues) { - if (!(nameElement is null)) + if (nameElement is not null && + _elements.TryGetValue((X500NameElement)nameElement, out byte[]? encodedValue)) { - if (_elements.TryGetValue((X500NameElement)nameElement, out byte[]? encodedValue)) - { - tlvWriter.WriteEncoded(encodedValue); - count++; - } + tlvWriter.WriteEncoded(encodedValue); + count++; } } diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/U2f/CommandTests.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/U2f/CommandTests.cs index 7c4f3c5a3..57169107b 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/U2f/CommandTests.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/U2f/CommandTests.cs @@ -28,12 +28,9 @@ public class CommandTests : IDisposable public CommandTests() { - if (SdkPlatformInfo.OperatingSystem == SdkPlatform.Windows) + if (SdkPlatformInfo.OperatingSystem == SdkPlatform.Windows && !SdkPlatformInfo.IsElevated) { - if (!SdkPlatformInfo.IsElevated) - { - throw new ArgumentException("Windows not elevated."); - } + throw new ArgumentException("Windows not elevated."); } IEnumerable devices = HidDevice.GetHidDevices(); diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/U2f/PinTests.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/U2f/PinTests.cs index a7a074177..d25cf6df7 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/U2f/PinTests.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/U2f/PinTests.cs @@ -29,12 +29,9 @@ public class PinTests : IDisposable public PinTests() { - if (SdkPlatformInfo.OperatingSystem == SdkPlatform.Windows) + if (SdkPlatformInfo.OperatingSystem == SdkPlatform.Windows && !SdkPlatformInfo.IsElevated) { - if (!SdkPlatformInfo.IsElevated) - { - throw new ArgumentException("Windows not elevated."); - } + throw new ArgumentException("Windows not elevated."); } var devices = HidDevice.GetHidDevices(); diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/U2f/SessionPinTests.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/U2f/SessionPinTests.cs index c7e14549a..426828d3c 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/U2f/SessionPinTests.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/U2f/SessionPinTests.cs @@ -26,12 +26,9 @@ public class SessionPinTests public SessionPinTests() { - if (SdkPlatformInfo.OperatingSystem == SdkPlatform.Windows) + if (SdkPlatformInfo.OperatingSystem == SdkPlatform.Windows && !SdkPlatformInfo.IsElevated) { - if (!SdkPlatformInfo.IsElevated) - { - throw new ArgumentException("Windows not elevated."); - } + throw new ArgumentException("Windows not elevated."); } IEnumerable yubiKeys = YubiKeyDevice.FindByTransport(Transport.HidFido); diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/U2f/SessionRegisterTests.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/U2f/SessionRegisterTests.cs index e46a34584..a3e9b6a38 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/U2f/SessionRegisterTests.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/U2f/SessionRegisterTests.cs @@ -27,12 +27,9 @@ public class SessionRegisterTests public SessionRegisterTests() { - if (SdkPlatformInfo.OperatingSystem == SdkPlatform.Windows) + if (SdkPlatformInfo.OperatingSystem == SdkPlatform.Windows && !SdkPlatformInfo.IsElevated) { - if (!SdkPlatformInfo.IsElevated) - { - throw new ArgumentException("Windows not elevated."); - } + throw new ArgumentException("Windows not elevated."); } IEnumerable yubiKeys = YubiKeyDevice.FindByTransport(Transport.HidFido | Transport.UsbSmartCard); diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/U2f/SetDeviceInfoTests.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/U2f/SetDeviceInfoTests.cs index f8e997e6a..f56be5b53 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/U2f/SetDeviceInfoTests.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/U2f/SetDeviceInfoTests.cs @@ -27,12 +27,9 @@ public class SetDeviceInfoTests : IDisposable public SetDeviceInfoTests() { - if (SdkPlatformInfo.OperatingSystem == SdkPlatform.Windows) + if (SdkPlatformInfo.OperatingSystem == SdkPlatform.Windows && !SdkPlatformInfo.IsElevated) { - if (!SdkPlatformInfo.IsElevated) - { - throw new ArgumentException("Windows not elevated."); - } + throw new ArgumentException("Windows not elevated."); } IEnumerable devices = HidDevice.GetHidDevices(); diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/U2f/SimpleU2fTests.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/U2f/SimpleU2fTests.cs index 1f61c037a..9523fc6fc 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/U2f/SimpleU2fTests.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/U2f/SimpleU2fTests.cs @@ -28,13 +28,10 @@ public class SimpleU2FTests [Fact] public void GetList_Succeeds() { - if (SdkPlatformInfo.OperatingSystem == SdkPlatform.Windows) + if (SdkPlatformInfo.OperatingSystem == SdkPlatform.Windows && !SdkPlatformInfo.IsElevated) { - if (!SdkPlatformInfo.IsElevated) - { - _ = Assert.Throws(() => YubiKeyDevice.FindByTransport(Transport.HidFido)); - Assert.True(false); - } + _ = Assert.Throws(() => YubiKeyDevice.FindByTransport(Transport.HidFido)); + Assert.True(false); } IEnumerable yubiKeys = YubiKeyDevice.FindByTransport(Transport.HidFido); @@ -46,13 +43,10 @@ public void GetList_Succeeds() [Fact] public void U2fCommand_Succeeds() { - if (SdkPlatformInfo.OperatingSystem == SdkPlatform.Windows) + if (SdkPlatformInfo.OperatingSystem == SdkPlatform.Windows && !SdkPlatformInfo.IsElevated) { - if (!SdkPlatformInfo.IsElevated) - { - _ = Assert.Throws(() => YubiKeyDevice.FindByTransport(Transport.HidFido)); - Assert.True(false); - } + _ = Assert.Throws(() => YubiKeyDevice.FindByTransport(Transport.HidFido)); + Assert.True(false); } IEnumerable devices = HidDevice.GetHidDevices(); @@ -119,13 +113,10 @@ public void U2fHid_U2fInitNoData_ReturnsInvalidDataLength() [Fact] public void GetProtocolVersion_Succeeds() { - if (SdkPlatformInfo.OperatingSystem == SdkPlatform.Windows) + if (SdkPlatformInfo.OperatingSystem == SdkPlatform.Windows && !SdkPlatformInfo.IsElevated) { - if (!SdkPlatformInfo.IsElevated) - { - _ = Assert.Throws(() => YubiKeyDevice.FindByTransport(Transport.HidFido)); - Assert.True(false); - } + _ = Assert.Throws(() => YubiKeyDevice.FindByTransport(Transport.HidFido)); + Assert.True(false); } IEnumerable devices = HidDevice.GetHidDevices(); @@ -154,13 +145,10 @@ public void GetProtocolVersion_Succeeds() [InlineData(new byte[] { 0x01, 0x02, 0x03 })] public void EchoCommand_GetCorrectData(ReadOnlyMemory sendData) { - if (SdkPlatformInfo.OperatingSystem == SdkPlatform.Windows) + if (SdkPlatformInfo.OperatingSystem == SdkPlatform.Windows && !SdkPlatformInfo.IsElevated) { - if (!SdkPlatformInfo.IsElevated) - { - _ = Assert.Throws(() => YubiKeyDevice.FindByTransport(Transport.HidFido)); - Assert.True(false); - } + _ = Assert.Throws(() => YubiKeyDevice.FindByTransport(Transport.HidFido)); + Assert.True(false); } IEnumerable devices = HidDevice.GetHidDevices(); diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/U2f/U2fCommandTests.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/U2f/U2fCommandTests.cs index 96ac09564..2bf4a9d60 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/U2f/U2fCommandTests.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/U2f/U2fCommandTests.cs @@ -29,12 +29,9 @@ public class U2fCommandTests public U2fCommandTests() { - if (SdkPlatformInfo.OperatingSystem == SdkPlatform.Windows) + if (SdkPlatformInfo.OperatingSystem == SdkPlatform.Windows && !SdkPlatformInfo.IsElevated) { - if (!SdkPlatformInfo.IsElevated) - { - throw new ArgumentException("Windows not elevated."); - } + throw new ArgumentException("Windows not elevated."); } IEnumerable devices = HidDevice.GetHidDevices(); diff --git a/Yubico.YubiKey/tests/sandbox/Plugins/Otp/YubiOtp.cs b/Yubico.YubiKey/tests/sandbox/Plugins/Otp/YubiOtp.cs index c7da45d6e..288f074c0 100644 --- a/Yubico.YubiKey/tests/sandbox/Plugins/Otp/YubiOtp.cs +++ b/Yubico.YubiKey/tests/sandbox/Plugins/Otp/YubiOtp.cs @@ -312,28 +312,31 @@ private Uri UploadToYubiCloud() response.Content.ReadAsStringAsync().Result, typeof(YubiOtpResponse))!; - if (!response.IsSuccessStatusCode) + if (response.IsSuccessStatusCode) { - if (response.StatusCode == System.Net.HttpStatusCode.BadRequest) + return yubiOtp?.FinishUrl ?? throw new InvalidOperationException( + "The Yubico OTP server returned an invalid response."); + } + + if (response.StatusCode == System.Net.HttpStatusCode.BadRequest) + { + string[] errors = yubiOtp.Errors ?? Array.Empty(); + if (errors.Length == 0) { - string[] errors = yubiOtp.Errors ?? Array.Empty(); - if (errors.Length == 0) - { - throw new InvalidOperationException( - "Upload to Yubico OTP server failed with BAD_REQUEST (no details from server)."); - } - if (errors.Length == 1) - { - throw new InvalidOperationException( - $"Upload to Yubico OTP server failed with BAD_REQUEST ({GetYubiOtpErrors(errors).First()})."); - } - IEnumerable exceptions = GetYubiOtpErrors(errors) - .Select(e => new InvalidOperationException( - $"Upload to Yubico OTP server failed with BAD_REQUEST ({e})")); - throw new AggregateException( - "Errors encountered uploading to Yubico OTP server. See inner exceptions for details", - exceptions); + throw new InvalidOperationException( + "Upload to Yubico OTP server failed with BAD_REQUEST (no details from server)."); + } + if (errors.Length == 1) + { + throw new InvalidOperationException( + $"Upload to Yubico OTP server failed with BAD_REQUEST ({GetYubiOtpErrors(errors).First()})."); } + IEnumerable exceptions = GetYubiOtpErrors(errors) + .Select(e => new InvalidOperationException( + $"Upload to Yubico OTP server failed with BAD_REQUEST ({e})")); + throw new AggregateException( + "Errors encountered uploading to Yubico OTP server. See inner exceptions for details", + exceptions); } return yubiOtp?.FinishUrl ?? throw new InvalidOperationException( diff --git a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Fido2/Commands/CredMgmtDataTests.cs b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Fido2/Commands/CredMgmtDataTests.cs index 7c1757b2f..b020b2e17 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Fido2/Commands/CredMgmtDataTests.cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Fido2/Commands/CredMgmtDataTests.cs @@ -14,6 +14,7 @@ using System; using System.Collections.Generic; +using System.Linq; using Xunit; using Yubico.YubiKey.Fido2.Cose; @@ -202,20 +203,13 @@ public void CredMgm_Decode_CorrectCredIdTransports() bool isCorrect = false; CredentialManagementData mgmtData = GetFullCredMgmtData(out Dictionary expectedValues); object expected = expectedValues[CredIdTransports]; - if (!(mgmtData.CredentialId is null) && expected is string[] unboxedValue) + if (mgmtData.CredentialId is not null && + expected is string[] unboxedValue && + mgmtData.CredentialId.Transports is not null && + mgmtData.CredentialId.Transports.Count == unboxedValue.Length && + mgmtData.CredentialId.Transports.SequenceEqual(unboxedValue)) { - if (!(mgmtData.CredentialId.Transports is null) && mgmtData.CredentialId.Transports.Count == unboxedValue.Length) - { - int index = 0; - for (; index < unboxedValue.Length; index++) - { - if (mgmtData.CredentialId.Transports[index] != unboxedValue[index]) - { - break; - } - } - isCorrect = index >= unboxedValue.Length; - } + isCorrect = true; } Assert.True(isCorrect); @@ -255,12 +249,9 @@ public void CredMgm_Decode_CorrectCurve() bool isCorrect = false; CredentialManagementData mgmtData = GetFullCredMgmtData(out Dictionary expectedValues); object expected = expectedValues[PubKeyCurve]; - if (!(mgmtData.CredentialPublicKey is null) && expected is CoseEcCurve unboxedValue) + if (mgmtData.CredentialPublicKey is CoseEcPublicKey pubKey && expected is CoseEcCurve unboxedValue) { - if (mgmtData.CredentialPublicKey is CoseEcPublicKey pubKey) - { - isCorrect = unboxedValue == pubKey.Curve; - } + isCorrect = unboxedValue == pubKey.Curve; } Assert.True(isCorrect); @@ -272,12 +263,9 @@ public void CredMgm_Decode_CorrectX() bool isCorrect = false; CredentialManagementData mgmtData = GetFullCredMgmtData(out Dictionary expectedValues); object expected = expectedValues[PubKeyX]; - if (!(mgmtData.CredentialPublicKey is null) && expected is byte[] unboxedValue) + if (mgmtData.CredentialPublicKey is CoseEcPublicKey pubKey && expected is byte[] unboxedValue) { - if (mgmtData.CredentialPublicKey is CoseEcPublicKey pubKey) - { - isCorrect = MemoryExtensions.SequenceEqual(pubKey.XCoordinate.Span, unboxedValue); - } + isCorrect = MemoryExtensions.SequenceEqual(pubKey.XCoordinate.Span, unboxedValue); } Assert.True(isCorrect); @@ -289,12 +277,9 @@ public void CredMgm_Decode_CorrectY() bool isCorrect = false; CredentialManagementData mgmtData = GetFullCredMgmtData(out Dictionary expectedValues); object expected = expectedValues[PubKeyY]; - if (!(mgmtData.CredentialPublicKey is null) && expected is byte[] unboxedValue) + if (mgmtData.CredentialPublicKey is CoseEcPublicKey pubKey && expected is byte[] unboxedValue) { - if (mgmtData.CredentialPublicKey is CoseEcPublicKey pubKey) - { - isCorrect = MemoryExtensions.SequenceEqual(pubKey.YCoordinate.Span, unboxedValue); - } + isCorrect = MemoryExtensions.SequenceEqual(pubKey.YCoordinate.Span, unboxedValue); } Assert.True(isCorrect); diff --git a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Fido2/Fido2InfoTests.cs b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Fido2/Fido2InfoTests.cs index a7059587d..70ecbc864 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Fido2/Fido2InfoTests.cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Fido2/Fido2InfoTests.cs @@ -130,15 +130,11 @@ public void Decode_Options_Correct() { for (; index < correctKeys.Length; index++) { - if (fido2Info.Options.TryGetValue(correctKeys[index], out bool currentValue)) + if (!fido2Info.Options.TryGetValue(correctKeys[index], out bool currentValue) || + currentValue != correctValues[index]) { - if (currentValue == correctValues[index]) - { - continue; - } + break; } - - break; } } @@ -312,15 +308,12 @@ public void Decode_Algorithms_Correct() { string currentType = fido2Info.Algorithms[index].Item1; CoseAlgorithmIdentifier currentAlg = fido2Info.Algorithms[index].Item2; - if (currentType.Equals(correctTypes[index], StringComparison.Ordinal)) + + if (!currentType.Equals(correctTypes[index], StringComparison.Ordinal) || + currentAlg != correctAlgs[index]) { - if (currentAlg == correctAlgs[index]) - { - continue; - } + break; } - - break; } } @@ -507,15 +500,11 @@ public void Decode_Certifications_Correct() { for (; index < correctKeys.Length; index++) { - if (fido2Info.Certifications.TryGetValue(correctKeys[index], out int currentValue)) + if (!fido2Info.Certifications.TryGetValue(correctKeys[index], out int currentValue) || + currentValue != correctValues[index]) { - if (currentValue == correctValues[index]) - { - continue; - } + break; } - - break; } } diff --git a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/SimpleKeyCollector.cs b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/SimpleKeyCollector.cs index 04fdf6fa5..d9738d418 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/SimpleKeyCollector.cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/SimpleKeyCollector.cs @@ -53,12 +53,9 @@ public bool SimpleKeyCollectorDelegate(KeyEntryData keyEntryData) return false; } - if (!(keyEntryData.RetriesRemaining is null)) + if (keyEntryData.RetriesRemaining is not null && keyEntryData.RetriesRemaining == 1) { - if (keyEntryData.RetriesRemaining == 1) - { - return false; - } + return false; } } diff --git a/Yubico.YubiKey/tests/utilities/Yubico/YubiKey/TestUtilities/Fido2ResetForTest.cs b/Yubico.YubiKey/tests/utilities/Yubico/YubiKey/TestUtilities/Fido2ResetForTest.cs index 0cd0ae742..7b3c643ec 100644 --- a/Yubico.YubiKey/tests/utilities/Yubico/YubiKey/TestUtilities/Fido2ResetForTest.cs +++ b/Yubico.YubiKey/tests/utilities/Yubico/YubiKey/TestUtilities/Fido2ResetForTest.cs @@ -190,12 +190,9 @@ public ResponseStatus RunFido2Reset() var resetCmd = new ResetCommand(); ResetResponse resetRsp = fido2Session.Connection.SendCommand(resetCmd); - if (resetRsp.Status == ResponseStatus.Success && _setPin) + if (resetRsp.Status == ResponseStatus.Success && _setPin && !fido2Session.TrySetPin(_pin)) { - if (!fido2Session.TrySetPin(_pin)) - { - return ResponseStatus.Failed; - } + return ResponseStatus.Failed; } return resetRsp.Status; diff --git a/Yubico.YubiKey/tests/utilities/Yubico/YubiKey/TestUtilities/HollowConnection.cs b/Yubico.YubiKey/tests/utilities/Yubico/YubiKey/TestUtilities/HollowConnection.cs index 4ee573fa9..be1522401 100644 --- a/Yubico.YubiKey/tests/utilities/Yubico/YubiKey/TestUtilities/HollowConnection.cs +++ b/Yubico.YubiKey/tests/utilities/Yubico/YubiKey/TestUtilities/HollowConnection.cs @@ -69,44 +69,38 @@ public TResponse SendCommand(IYubiKeyCommand yubiKeyComman return yubiKeyCommand.CreateResponseForApdu(responseApdu); } - if (yubiKeyCommand is InitializeAuthenticateManagementKeyCommand) + if (yubiKeyCommand is InitializeAuthenticateManagementKeyCommand && AlwaysAuthenticatePiv) { - if (AlwaysAuthenticatePiv) - { - byte[] responseData = new byte[] { - 0x7C, 0x0A, 0x80, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x90, 0x00 - }; - var responseApdu = new ResponseApdu(responseData); - return yubiKeyCommand.CreateResponseForApdu(responseApdu); - } + byte[] responseData = new byte[] { + 0x7C, 0x0A, 0x80, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x90, 0x00 + }; + var responseApdu = new ResponseApdu(responseData); + return yubiKeyCommand.CreateResponseForApdu(responseApdu); } - if (yubiKeyCommand is CompleteAuthenticateManagementKeyCommand) + if (yubiKeyCommand is CompleteAuthenticateManagementKeyCommand && AlwaysAuthenticatePiv) { - if (AlwaysAuthenticatePiv) - { - CommandApdu apdu = yubiKeyCommand.CreateCommandApdu(); - byte[] data = apdu.Data.ToArray(); - byte[] responseData = new byte[] { - 0x7C, 0x0A, 0x82, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x90, 0x00 - }; - byte[] keyBytes = new byte[] { - 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, - 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, - 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08 - }; - Array.Copy(data, 14, responseData, 4, 8); - - using TripleDES tripleDes = CryptographyProviders.TripleDesCreator(); - - tripleDes.Mode = CipherMode.ECB; - tripleDes.Padding = PaddingMode.None; - using ICryptoTransform encryptor = tripleDes.CreateEncryptor(keyBytes, null); - _ = encryptor.TransformBlock(data, 14, 8, responseData, 4); - - var responseApdu = new ResponseApdu(responseData); - return yubiKeyCommand.CreateResponseForApdu(responseApdu); - } + CommandApdu apdu = yubiKeyCommand.CreateCommandApdu(); + byte[] data = apdu.Data.ToArray(); + byte[] responseData = new byte[] { + 0x7C, 0x0A, 0x82, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x90, 0x00 + }; + byte[] keyBytes = new byte[] { + 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, + 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, + 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08 + }; + Array.Copy(data, 14, responseData, 4, 8); + + using TripleDES tripleDes = CryptographyProviders.TripleDesCreator(); + + tripleDes.Mode = CipherMode.ECB; + tripleDes.Padding = PaddingMode.None; + using ICryptoTransform encryptor = tripleDes.CreateEncryptor(keyBytes, null); + _ = encryptor.TransformBlock(data, 14, 8, responseData, 4); + + var responseApdu = new ResponseApdu(responseData); + return yubiKeyCommand.CreateResponseForApdu(responseApdu); } if (yubiKeyCommand is ReadStatusCommand) diff --git a/Yubico.YubiKey/tests/utilities/Yubico/YubiKey/TestUtilities/StaticConverters.cs b/Yubico.YubiKey/tests/utilities/Yubico/YubiKey/TestUtilities/StaticConverters.cs index 52d649058..62f99fdf8 100644 --- a/Yubico.YubiKey/tests/utilities/Yubico/YubiKey/TestUtilities/StaticConverters.cs +++ b/Yubico.YubiKey/tests/utilities/Yubico/YubiKey/TestUtilities/StaticConverters.cs @@ -204,12 +204,9 @@ public static bool ParseBool(string s) /// public static T ParseEnum(string s) where T : struct { - if (Enum.TryParse(s, true, out T value)) + if (Enum.TryParse(s, true, out T value) && Enum.IsDefined(typeof(T), value)) { - if (Enum.IsDefined(typeof(T), value)) - { - return value; - } + return value; } throw new ArgumentException($"Value [{s}] could not be parsed as type [{typeof(T).Name}]."); }