diff --git a/.editorconfig b/.editorconfig index 0eb3fa03..d351c8aa 100644 --- a/.editorconfig +++ b/.editorconfig @@ -312,8 +312,6 @@ dotnet_diagnostic.CA2201.severity = none # CA2208: Instantiate argument exceptions correctly dotnet_diagnostic.CA2208.severity = none -[**/YubiPosh/**/*.cs] - # CA1014: Mark assemblies with CLSCompliantAttribute dotnet_diagnostic.CA1014.severity = none diff --git a/.github/workflows/check-code-formatting.yml b/.github/workflows/check-code-formatting.yml new file mode 100644 index 00000000..7828ba65 --- /dev/null +++ b/.github/workflows/check-code-formatting.yml @@ -0,0 +1,39 @@ +# Copyright 2021 Yubico AB +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +name: Check code formatting + +on: + pull_request: + branches: + - main + - 'develop**' + - 'release/**' + +jobs: + check-code-formatting: + runs-on: windows-2019 + + steps: + # Checkout the local repository + - uses: actions/checkout@v4 + + - name: Add local NuGet repository + run: dotnet nuget add source --username ${{ github.actor }} --password ${{ secrets.GITHUB_TOKEN }} --store-password-in-clear-text --name github "https://nuget.pkg.github.com/Yubico/index.json" + + - name: Build Yubico.NET.SDK.sln + run: dotnet build --configuration Release --nologo --verbosity normal Yubico.NET.SDK.sln + + - name: Check for correct formatting + run: dotnet format --verify-no-changes --no-restore -v d \ No newline at end of file diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml index 2731f404..a0bff54d 100644 --- a/.github/workflows/codeql-analysis.yml +++ b/.github/workflows/codeql-analysis.yml @@ -42,15 +42,15 @@ permissions: jobs: analyze: name: Analyze - runs-on: windows-2019 + runs-on: windows-2022 steps: - name: Checkout repository - uses: actions/checkout@v2 + uses: actions/checkout@v4 # Initializes the CodeQL tools for scanning. - name: Initialize CodeQL - uses: github/codeql-action/init@v2 + uses: github/codeql-action/init@v3 with: languages: csharp @@ -62,4 +62,4 @@ jobs: run: dotnet build --configuration Release --nologo --verbosity normal Yubico.NET.SDK.sln - name: Perform CodeQL Analysis - uses: github/codeql-action/analyze@v2 + uses: github/codeql-action/analyze@v3 diff --git a/.github/workflows/cross-build-nativeshims.yml b/.github/workflows/cross-build-nativeshims.yml index 26b9a4c8..b261b88c 100644 --- a/.github/workflows/cross-build-nativeshims.yml +++ b/.github/workflows/cross-build-nativeshims.yml @@ -24,7 +24,7 @@ on: version: description: 'Version' required: false - default: "0.0.0-prerelease.YYYMMDD.B" + default: "0.0.0-prerelease.YYYYMMDD.B" type: string jobs: @@ -32,65 +32,72 @@ jobs: name: Build Windows runs-on: windows-2019 steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v4 - run: | + echo 'Running build script: Windows' cd Yubico.NativeShims - ./build-windows.cmd - - uses: actions/upload-artifact@v3 + & ./build-windows.ps1 + - uses: actions/upload-artifact@v4 with: name: win-x64 path: Yubico.NativeShims/win-x64/** - - uses: actions/upload-artifact@v3 + - uses: actions/upload-artifact@v4 with: name: win-x86 path: Yubico.NativeShims/win-x86/** - - uses: actions/upload-artifact@v3 + - uses: actions/upload-artifact@v4 with: name: win-arm64 path: Yubico.NativeShims/win-arm64/** - - uses: actions/upload-artifact@v3 + - uses: actions/upload-artifact@v4 with: name: nuspec path: Yubico.NativeShims/*.nuspec - - uses: actions/upload-artifact@v3 + - uses: actions/upload-artifact@v4 with: name: msbuild path: Yubico.NativeShims/msbuild/* - build-ubuntu: - name: Build Ubuntu - runs-on: ubuntu-latest + build-linux-amd64: + name: Build Linux (amd64) + runs-on: ubuntu-20.04 steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v4 - run: | + echo 'Running build script: Linux (amd64)' cd Yubico.NativeShims - sh ./build-ubuntu.sh - - uses: actions/upload-artifact@v3 + sh ./build-linux-amd64.sh + - uses: actions/upload-artifact@v4 with: - name: ubuntu-x64 - path: Yubico.NativeShims/ubuntu-x64/** - - uses: actions/upload-artifact@v3 - with: - name: ubuntu-x86 - path: Yubico.NativeShims/ubuntu-x86/** - - uses: actions/upload-artifact@v3 + name: linux-x64 + path: Yubico.NativeShims/linux-x64/*.so + build-linux-arm64: + name: Build Linux (arm64) + runs-on: ubuntu-20.04 + steps: + - uses: actions/checkout@v4 + - run: | + echo 'Running build script: Linux (arm64)' + cd Yubico.NativeShims + sh ./build-linux-arm64.sh + - uses: actions/upload-artifact@v4 with: - name: ubuntu-arm64 - path: Yubico.NativeShims/ubuntu-arm64/** - + name: linux-arm64 + path: Yubico.NativeShims/linux-arm64/*.so build-macos: name: Build macOS runs-on: macos-latest steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v4 - run: | + echo 'Running build script: macOS' cd Yubico.NativeShims sh ./build-macOS.sh - - uses: actions/upload-artifact@v3 + - uses: actions/upload-artifact@v4 with: name: osx-x64 path: Yubico.NativeShims/osx-x64/** - - uses: actions/upload-artifact@v3 + - uses: actions/upload-artifact@v4 with: name: osx-arm64 path: Yubico.NativeShims/osx-arm64/** @@ -98,9 +105,9 @@ jobs: pack: name: Package artifacts runs-on: windows-2019 - needs: [build-windows, build-ubuntu, build-macos] + needs: [build-windows, build-linux-amd64, build-linux-arm64, build-macos] steps: - - uses: actions/download-artifact@v3 + - uses: actions/download-artifact@v4 - run: | mv nuspec/*.nuspec . del nuspec @@ -113,7 +120,7 @@ jobs: $nuspec.Save("Yubico.NativeShims.nuspec") cat Yubico.NativeShims.nuspec - run: nuget pack Yubico.NativeShims.nuspec - - uses: actions/upload-artifact@v3 + - uses: actions/upload-artifact@v4 with: name: Yubico.NativeShims.nupkg path: Yubico.NativeShims.*.nupkg @@ -123,9 +130,11 @@ jobs: runs-on: windows-2019 needs: pack environment: Internal NuGet feed + permissions: + packages: write if: ${{ github.event.inputs.push-to-dev == 'true' }} steps: - - uses: actions/download-artifact@v3 + - uses: actions/download-artifact@v4 with: name: Yubico.NativeShims.nupkg - run: | diff --git a/.github/workflows/pull-requests.yml b/.github/workflows/pull-requests.yml index 8c589c22..6cd4ea1a 100644 --- a/.github/workflows/pull-requests.yml +++ b/.github/workflows/pull-requests.yml @@ -33,7 +33,7 @@ jobs: # Even though we build for multiple platforms, we only need to run # on a single host operating system. This is because we utilize cross- # build functionality of the dotnet build system. - runs-on: windows-2019 + runs-on: windows-latest # Build both Debug and ReleaseWithDocs configurations. Most people are probably building 'Debug' the most often. We # should be sure that Release also builds, and that our documentation also compiles successfully. strategy: @@ -42,22 +42,24 @@ jobs: steps: # Checkout the local repository - - uses: actions/checkout@v2 + - uses: actions/checkout@v4 + - uses: actions/setup-dotnet@v4 + with: + global-json-file: global.json + + - name: run dotnet version + run: dotnet --version - name: Add local NuGet repository run: dotnet nuget add source --username ${{ github.actor }} --password ${{ secrets.GITHUB_TOKEN }} --store-password-in-clear-text --name github "https://nuget.pkg.github.com/Yubico/index.json" # Build the project - # The default GitHub runners seem to have N and N-1 versions of .NET Framework installed. In practice, they seem - # to have even more installed than that, but at a minimum N and N-1 seem like safe assumptions. We can therefore - # save some time and use the pre-installed version rather than downloading a fresh copy. - - name: Build Yubico.NET.SDK.sln run: dotnet build --configuration ${{matrix.configuration}} --nologo --verbosity normal Yubico.NET.SDK.sln # Save the built NuGet packages, just in case we need to inspect the build output. - name: Save build artifacts - uses: actions/upload-artifact@v2 + uses: actions/upload-artifact@v4 with: name: Nuget Packages ${{matrix.configuration}} path: | @@ -66,7 +68,7 @@ jobs: Yubico.YubiKey/src/bin/${{matrix.configuration}}/*.nupkg - name: Save build artifacts - uses: actions/upload-artifact@v2 + uses: actions/upload-artifact@v4 with: name: Assemblies ${{matrix.configuration}} path: | diff --git a/.github/workflows/test-and-cover.yml b/.github/workflows/test-and-cover.yml new file mode 100644 index 00000000..bef7e328 --- /dev/null +++ b/.github/workflows/test-and-cover.yml @@ -0,0 +1,97 @@ +# Copyright 2021 Yubico AB +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +name: Tests and code coverage + +on: + pull_request: + branches: + - main + - 'develop**' + - 'release/**' + +jobs: + test: + runs-on: windows-2019 + + steps: + - uses: actions/checkout@v4 + + - name: Add local NuGet repository + run: dotnet nuget add source --username ${{ github.actor }} --password ${{ secrets.GITHUB_TOKEN }} --store-password-in-clear-text --name github "https://nuget.pkg.github.com/Yubico/index.json" + + - name: Test Yubico.YubiKey + run: dotnet test --configuration Release --nologo --logger trx --collect:"XPlat Code Coverage" Yubico.YubiKey/tests/unit/Yubico.YubiKey.UnitTests.csproj --settings coverlet.runsettings.xml + + - name: Test Yubico.Core + run: dotnet test --configuration Release --nologo --logger trx --collect:"XPlat Code Coverage" Yubico.Core/tests/Yubico.Core.UnitTests.csproj --settings coverlet.runsettings.xml + + - name: Upload Test Result Files + uses: actions/upload-artifact@v4 + with: + name: TestResults + if-no-files-found: error + path: '**/TestResults/*' + + coverage: + permissions: + contents: read + issues: read + checks: write + pull-requests: write + runs-on: ubuntu-latest + needs: test + steps: + - uses: actions/download-artifact@v4 + with: + name: TestResults + path: ${{ github.workspace }} + + - name: Combine Coverage Reports # This is because one report is produced per project, and we want one result for all of them. + uses: danielpalme/ReportGenerator-GitHub-Action@5.2.4 + with: + reports: "**/*.cobertura.xml" # REQUIRED # The coverage reports that should be parsed (separated by semicolon). Globbing is supported. + targetdir: "${{ github.workspace }}" # REQUIRED # The directory where the generated report should be saved. + reporttypes: "Cobertura" # The output formats and scope (separated by semicolon) Values: Badges, Clover, Cobertura, CsvSummary, Html, Html_Dark, Html_Light, Html_BlueRed, HtmlChart, HtmlInline, HtmlInline_AzurePipelines, HtmlInline_AzurePipelines_Dark, HtmlInline_AzurePipelines_Light, HtmlSummary, JsonSummary, Latex, LatexSummary, lcov, MarkdownSummary, MarkdownSummaryGithub, MarkdownDeltaSummary, MHtml, PngChart, SonarQube, TeamCitySummary, TextSummary, TextDeltaSummary, Xml, XmlSummary + verbosity: "Info" # The verbosity level of the log messages. Values: Verbose, Info, Warning, Error, Off + title: "Code Coverage" # Optional title. + tag: "${{ github.run_number }}_${{ github.run_id }}" # Optional tag or build version. + customSettings: "" # Optional custom settings (separated by semicolon). See: https://github.com/danielpalme/ReportGenerator/wiki/Settings. + toolpath: "reportgeneratortool" # Default directory for installing the dotnet tool. + + - name: Publish Code Coverage Report + uses: irongut/CodeCoverageSummary@v1.3.0 + with: + filename: "Cobertura.xml" + badge: true + fail_below_min: true + format: markdown + hide_branch_rate: false + hide_complexity: false + indicators: true + output: both + thresholds: "50 70" + + - name: Add Coverage PR Comment + uses: marocchino/sticky-pull-request-comment@v2.9.0 + if: github.event_name == 'pull_request' + with: + recreate: true + path: code-coverage-results.md + + - name: Publish Test Results + uses: EnricoMi/publish-unit-test-result-action@v2.16.1 + if: always() + with: + trx_files: "${{ github.workspace }}/**/*.trx" \ No newline at end of file diff --git a/.gitignore b/.gitignore index 52a158bc..e6cbea51 100644 --- a/.gitignore +++ b/.gitignore @@ -9,7 +9,7 @@ Yubico.NativeShims/build*/ Yubico.NativeShims/Yubico.NativeShims.h Yubico.NativeShims/win-* Yubico.NativeShims/osx-* -Yubico.NativeShims/ubuntu-* +Yubico.NativeShims/linux-* # NuGet config # We treat NuGet configs as per-user settings @@ -551,3 +551,7 @@ cython_debug/ # XML Documentation Output /Yubico.Core/src/Yubico.Core.xml /Yubico.YubiKey/src/Yubico.YubiKey.xml + +# Coverage / Test Results +coveragereport/ +TestResults/ \ No newline at end of file diff --git a/README.md b/README.md index 2f16ae24..29a43a64 100644 --- a/README.md +++ b/README.md @@ -12,6 +12,9 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> +> Dev: ![tests-dev](https://github.com/Yubico/Yubico.NET.SDK-private/actions/workflows/test-and-cover.yml/badge.svg?branch=yesdk-1315-skip-unsuitable-tests) +> Main: ![tests-main](https://github.com/Yubico/Yubico.NET.SDK-private/actions/workflows/test-and-cover.yml/badge.svg?branch=main) + # .NET YubiKey SDK This is a cross-platform, all encompassing SDK for the YubiKey aimed at large to mid-sized enterprise diff --git a/Yubico.Core/src/AssemblyInfo.cs b/Yubico.Core/src/AssemblyInfo.cs index b1da9f09..a8b816ed 100644 --- a/Yubico.Core/src/AssemblyInfo.cs +++ b/Yubico.Core/src/AssemblyInfo.cs @@ -14,4 +14,4 @@ using System; -[assembly:CLSCompliant(true)] +[assembly: CLSCompliant(true)] diff --git a/Yubico.Core/src/Yubico.Core.csproj b/Yubico.Core/src/Yubico.Core.csproj index b4924a02..55f20805 100644 --- a/Yubico.Core/src/Yubico.Core.csproj +++ b/Yubico.Core/src/Yubico.Core.csproj @@ -111,6 +111,7 @@ limitations under the License. --> + diff --git a/Yubico.Core/src/Yubico/Core/Buffers/Base16.cs b/Yubico.Core/src/Yubico/Core/Buffers/Base16.cs index d79dffa3..d3aa8bd2 100644 --- a/Yubico.Core/src/Yubico/Core/Buffers/Base16.cs +++ b/Yubico.Core/src/Yubico/Core/Buffers/Base16.cs @@ -58,7 +58,7 @@ public class Base16 : ITextEncoding /// public void Encode(ReadOnlySpan data, Span encoded) { - if (data.Length > (encoded.Length * 2)) + if (data.Length > encoded.Length * 2) { throw new ArgumentException( nameof(encoded), diff --git a/Yubico.Core/src/Yubico/Core/Cryptography/AesGcmPrimitivesOpenSsl.cs b/Yubico.Core/src/Yubico/Core/Cryptography/AesGcmPrimitivesOpenSsl.cs index c8f1f16b..53cd3601 100644 --- a/Yubico.Core/src/Yubico/Core/Cryptography/AesGcmPrimitivesOpenSsl.cs +++ b/Yubico.Core/src/Yubico/Core/Cryptography/AesGcmPrimitivesOpenSsl.cs @@ -38,8 +38,8 @@ public void EncryptAndAuthenticate( Span tag, ReadOnlySpan associatedData) { - if ((nonce.Length != NonceLength) || (ciphertext.Length != plaintext.Length) - || (tag.Length != AuthTagLength)) + if (nonce.Length != NonceLength || ciphertext.Length != plaintext.Length + || tag.Length != AuthTagLength) { throw new ArgumentException(ExceptionMessages.InvalidAesGcmInput); } @@ -102,7 +102,7 @@ public void EncryptAndAuthenticate( } /// - public bool DecryptAndVerify ( + public bool DecryptAndVerify( ReadOnlySpan keyData, ReadOnlySpan nonce, ReadOnlySpan ciphertext, @@ -110,8 +110,8 @@ public bool DecryptAndVerify ( Span plaintext, ReadOnlySpan associatedData) { - if ((nonce.Length != NonceLength) || (plaintext.Length != ciphertext.Length) - || (tag.Length != AuthTagLength)) + if (nonce.Length != NonceLength || plaintext.Length != ciphertext.Length + || tag.Length != AuthTagLength) { throw new ArgumentException(ExceptionMessages.InvalidAesGcmInput); } diff --git a/Yubico.Core/src/Yubico/Core/Cryptography/EcParametersSslExtensions.cs b/Yubico.Core/src/Yubico/Core/Cryptography/EcParametersSslExtensions.cs index 436866b7..1403b5f2 100644 --- a/Yubico.Core/src/Yubico/Core/Cryptography/EcParametersSslExtensions.cs +++ b/Yubico.Core/src/Yubico/Core/Cryptography/EcParametersSslExtensions.cs @@ -80,7 +80,7 @@ _ when curve.HasSameOid(ECCurve.NamedCurves.nistP521) => 716, /// /// This function only supports the NIST P256, P384, and P512 curves as of version 1.5.0. /// - public static int BitLength (this ECCurve curve) => + public static int BitLength(this ECCurve curve) => curve switch { _ when curve.HasSameOid(ECCurve.NamedCurves.nistP256) => NistP256BitLength, diff --git a/Yubico.Core/src/Yubico/Core/Cryptography/IAesGcmPrimitives.cs b/Yubico.Core/src/Yubico/Core/Cryptography/IAesGcmPrimitives.cs index 3d5ae879..b4aaa976 100644 --- a/Yubico.Core/src/Yubico/Core/Cryptography/IAesGcmPrimitives.cs +++ b/Yubico.Core/src/Yubico/Core/Cryptography/IAesGcmPrimitives.cs @@ -138,7 +138,7 @@ public void EncryptAndAuthenticate( /// One of the arguments was not valid (e.g. tag is not exactly 16 /// bytes). /// - public bool DecryptAndVerify ( + public bool DecryptAndVerify( ReadOnlySpan keyData, ReadOnlySpan nonce, ReadOnlySpan ciphertext, diff --git a/Yubico.Core/src/Yubico/Core/Devices/Hid/HidCodeTranslator.cs b/Yubico.Core/src/Yubico/Core/Devices/Hid/HidCodeTranslator.cs index ffd7ad94..9f117f2e 100644 --- a/Yubico.Core/src/Yubico/Core/Devices/Hid/HidCodeTranslator.cs +++ b/Yubico.Core/src/Yubico/Core/Devices/Hid/HidCodeTranslator.cs @@ -40,18 +40,17 @@ private HidCodeTranslator( #endregion #region Private fields - private static readonly Dictionary _lookup - = new Dictionary - { - [KeyboardLayout.en_US] = GetEN_US(), - [KeyboardLayout.en_UK] = GetEN_UK(), - [KeyboardLayout.de_DE] = GetDE_DE(), - [KeyboardLayout.fr_FR] = GetFR_FR(), - [KeyboardLayout.it_IT] = GetIT_IT(), - [KeyboardLayout.es_US] = GetES_US(), - [KeyboardLayout.sv_SE] = GetSV_SE(), - [KeyboardLayout.ModHex] = GetModHex() - }; + private static readonly Dictionary _lookup = new Dictionary + { + [KeyboardLayout.en_US] = GetEN_US(), + [KeyboardLayout.en_UK] = GetEN_UK(), + [KeyboardLayout.de_DE] = GetDE_DE(), + [KeyboardLayout.fr_FR] = GetFR_FR(), + [KeyboardLayout.it_IT] = GetIT_IT(), + [KeyboardLayout.es_US] = GetES_US(), + [KeyboardLayout.sv_SE] = GetSV_SE(), + [KeyboardLayout.ModHex] = GetModHex() + }; private readonly Dictionary _byChar; private readonly Dictionary _byCode; #endregion diff --git a/Yubico.Core/src/Yubico/Core/Devices/Hid/IOKitHelpers.cs b/Yubico.Core/src/Yubico/Core/Devices/Hid/IOKitHelpers.cs index 998ebd2b..9d53ebd2 100644 --- a/Yubico.Core/src/Yubico/Core/Devices/Hid/IOKitHelpers.cs +++ b/Yubico.Core/src/Yubico/Core/Devices/Hid/IOKitHelpers.cs @@ -51,9 +51,9 @@ public static int GetIntPropertyValue(IntPtr device, string propertyName) // We want to rely on Nullable's null checking and subsequent exception. // Rather than duplicate the messaging and exception ourselves, let's just // use theirs. - #pragma warning disable CS8629 +#pragma warning disable CS8629 return propertyValue.Value; - #pragma warning restore CS8629 +#pragma warning restore CS8629 } /// diff --git a/Yubico.Core/src/Yubico/Core/Devices/Hid/LinuxHidDevice.cs b/Yubico.Core/src/Yubico/Core/Devices/Hid/LinuxHidDevice.cs index 58e5629f..5ddbe2d9 100644 --- a/Yubico.Core/src/Yubico/Core/Devices/Hid/LinuxHidDevice.cs +++ b/Yubico.Core/src/Yubico/Core/Devices/Hid/LinuxHidDevice.cs @@ -13,8 +13,8 @@ // limitations under the License. using System; -using System.Runtime.InteropServices; using System.Collections.Generic; +using System.Runtime.InteropServices; using Yubico.Core.Logging; using Yubico.PlatformInterop; @@ -210,7 +210,7 @@ private void ParseUsageProperties(byte[] descriptor, int offset, int descriptorL // If the tag is 4, the value is the USAGE PAGE. If we already // have a USAGE PAGE, ignore this one. - if ((tag == UsagePageTag) && (!usagePageFound)) + if (tag == UsagePageTag && !usagePageFound) { usagePageValue = value; usagePageFound = true; @@ -218,7 +218,7 @@ private void ParseUsageProperties(byte[] descriptor, int offset, int descriptorL // If the tag is 8, the value is the USAGE. Go ahead and set the // Usage property in this object. If we already have a USAGE, // ignore this one. - else if ((tag == UsageTag) && (!usageFound)) + else if (tag == UsageTag && !usageFound) { Usage = (short)value; usageFound = true; @@ -234,11 +234,11 @@ private void ParseUsageProperties(byte[] descriptor, int offset, int descriptorL // If it is not a valid combo, don't set the UsagePage. // We set the Usage even though it might be one we don't support, // because if the UsagePage is Unknown, the Usage won't matter. - if ((usagePageValue == UsagePageGeneric) && (Usage == UsageKeyboard)) + if (usagePageValue == UsagePageGeneric && Usage == UsageKeyboard) { UsagePage = HidUsagePage.Keyboard; } - else if ((usagePageValue == UsagePageFido) && (Usage == UsageU2FDevice)) + else if (usagePageValue == UsagePageFido && Usage == UsageU2FDevice) { UsagePage = HidUsagePage.Fido; } @@ -296,7 +296,7 @@ private static int ReadValue(byte[] descriptor, int offset, int descriptorLength int newOffset = offset + length; - if ((length <= 4) && (length + offset <= descriptorLength)) + if (length <= 4 && length + offset <= descriptorLength) { for (int index = 0; index < length; index++) { diff --git a/Yubico.Core/src/Yubico/Core/Devices/Hid/LinuxHidDeviceListener.cs b/Yubico.Core/src/Yubico/Core/Devices/Hid/LinuxHidDeviceListener.cs index 63157b50..1d725e1c 100644 --- a/Yubico.Core/src/Yubico/Core/Devices/Hid/LinuxHidDeviceListener.cs +++ b/Yubico.Core/src/Yubico/Core/Devices/Hid/LinuxHidDeviceListener.cs @@ -52,7 +52,7 @@ public LinuxHidDeviceListener() { _udevObject = udev_new(); _monitorObject = ThrowIfFailedNull(udev_monitor_new_from_netlink(_udevObject, UdevMonitorName)); - + RemoveNonBlockingFlagOnUdevMonitorSocket(); StartListening(); @@ -197,8 +197,8 @@ private void RemoveNonBlockingFlagOnUdevMonitorSocket() { IntPtr fd = udev_monitor_get_fd(_monitorObject); - int flags = ThrowIfFailedNegative(fcntl(fd, F_GETFL)); - + int flags = ThrowIfFailedNegative(fcntl(fd, F_GETFL)); + // Remove the O_NONBLOCK flag to set the file descriptor to blocking mode. _ = ThrowIfFailedNegative(fcntl(fd, F_SETFL, flags & ~O_NONBLOCK)); } diff --git a/Yubico.Core/src/Yubico/Core/Devices/Hid/LinuxHidFeatureReportConnection.cs b/Yubico.Core/src/Yubico/Core/Devices/Hid/LinuxHidFeatureReportConnection.cs index f544c763..867409bb 100644 --- a/Yubico.Core/src/Yubico/Core/Devices/Hid/LinuxHidFeatureReportConnection.cs +++ b/Yubico.Core/src/Yubico/Core/Devices/Hid/LinuxHidFeatureReportConnection.cs @@ -13,8 +13,8 @@ // limitations under the License. using System; -using System.Linq; using System.Globalization; +using System.Linq; using System.Runtime.InteropServices; using Yubico.PlatformInterop; diff --git a/Yubico.Core/src/Yubico/Core/Devices/SmartCard/SmartCardDevice.cs b/Yubico.Core/src/Yubico/Core/Devices/SmartCard/SmartCardDevice.cs index 26390725..20592a8a 100644 --- a/Yubico.Core/src/Yubico/Core/Devices/SmartCard/SmartCardDevice.cs +++ b/Yubico.Core/src/Yubico/Core/Devices/SmartCard/SmartCardDevice.cs @@ -15,8 +15,8 @@ using System; using System.Collections.Generic; using Yubico.Core.Iso7816; -using Yubico.PlatformInterop; using Yubico.Core.Logging; +using Yubico.PlatformInterop; namespace Yubico.Core.Devices.SmartCard { diff --git a/Yubico.Core/src/Yubico/Core/Iso7816/CommandApdu.cs b/Yubico.Core/src/Yubico/Core/Iso7816/CommandApdu.cs index add3a08a..a0b05ebb 100644 --- a/Yubico.Core/src/Yubico/Core/Iso7816/CommandApdu.cs +++ b/Yubico.Core/src/Yubico/Core/Iso7816/CommandApdu.cs @@ -93,7 +93,7 @@ public int Ne { if (value < 0) { - throw new ArgumentOutOfRangeException(nameof(Ne),ExceptionMessages.CommandApduNeRangeError); + throw new ArgumentOutOfRangeException(nameof(Ne), ExceptionMessages.CommandApduNeRangeError); } else { @@ -214,7 +214,7 @@ private bool ValidNe(ApduEncoding apduEncoding) { int inclusiveUpperBound = GetInclusiveUpperBound(apduEncoding); - return (Ne == int.MaxValue) || (Ne >= 0 && Ne <= inclusiveUpperBound); + return Ne == int.MaxValue || (Ne >= 0 && Ne <= inclusiveUpperBound); } // Validates Nc, then returns the Lc field as a byte array in the given encoding. diff --git a/Yubico.Core/src/Yubico/Core/Tlv/TlvEncoder.cs b/Yubico.Core/src/Yubico/Core/Tlv/TlvEncoder.cs index df7bb80c..df76c017 100644 --- a/Yubico.Core/src/Yubico/Core/Tlv/TlvEncoder.cs +++ b/Yubico.Core/src/Yubico/Core/Tlv/TlvEncoder.cs @@ -126,7 +126,7 @@ public static byte[] BuildTagAndLength(int tag, int length) /// public static void VerifyTag(int tag) { - if ((tag < 0) || (tag > MaximumTag)) + if (tag < 0 || tag > MaximumTag) { throw new TlvException(ExceptionMessages.TlvUnsupportedTag); } @@ -148,7 +148,7 @@ public static void VerifyTag(int tag) /// public static void VerifyLength(int length) { - if ((length < 0) || (length > MaximumLength)) + if (length < 0 || length > MaximumLength) { throw new TlvException(ExceptionMessages.TlvUnsupportedLengthField); } diff --git a/Yubico.Core/src/Yubico/Core/Tlv/TlvNestedTlv.cs b/Yubico.Core/src/Yubico/Core/Tlv/TlvNestedTlv.cs index b29e0517..ab398925 100644 --- a/Yubico.Core/src/Yubico/Core/Tlv/TlvNestedTlv.cs +++ b/Yubico.Core/src/Yubico/Core/Tlv/TlvNestedTlv.cs @@ -128,7 +128,7 @@ public void AddSubElement(TlvEncoder subElement) override public bool TryEncode(Span encoding, int offset, out int bytesWritten) { bytesWritten = 0; - if (encoding.Length < (offset + _encodedLength)) + if (encoding.Length < offset + _encodedLength) { return false; } diff --git a/Yubico.Core/src/Yubico/Core/Tlv/TlvReader.cs b/Yubico.Core/src/Yubico/Core/Tlv/TlvReader.cs index f23c781a..0f3f5f27 100644 --- a/Yubico.Core/src/Yubico/Core/Tlv/TlvReader.cs +++ b/Yubico.Core/src/Yubico/Core/Tlv/TlvReader.cs @@ -418,7 +418,7 @@ public bool TryReadByte(out byte value, int expectedTag) FixedLengthByte, false); - if (isValid == true) + if (isValid) { value = fullValue.Span[0]; } @@ -474,7 +474,7 @@ public short ReadInt16(int expectedTag, bool bigEndian = true) { _ = CommonReadValue(out ReadOnlyMemory value, expectedTag, FixedLengthInt16, true); - if (bigEndian == true) + if (bigEndian) { return BinaryPrimitives.ReadInt16BigEndian(value.Span); } @@ -528,9 +528,9 @@ public bool TryReadInt16(out short value, int expectedTag, bool bigEndian = true FixedLengthInt16, false); - if (isValid == true) + if (isValid) { - if (bigEndian == true) + if (bigEndian) { value = BinaryPrimitives.ReadInt16BigEndian(fullValue.Span); } @@ -591,7 +591,7 @@ public ushort ReadUInt16(int expectedTag, bool bigEndian = true) { _ = CommonReadValue(out ReadOnlyMemory value, expectedTag, FixedLengthInt16, true); - if (bigEndian == true) + if (bigEndian) { return BinaryPrimitives.ReadUInt16BigEndian(value.Span); } @@ -646,9 +646,9 @@ public bool TryReadUInt16(out ushort value, int expectedTag, bool bigEndian = tr FixedLengthInt16, false); - if (isValid == true) + if (isValid) { - if (bigEndian == true) + if (bigEndian) { value = BinaryPrimitives.ReadUInt16BigEndian(fullValue.Span); } @@ -709,7 +709,7 @@ public int ReadInt32(int expectedTag, bool bigEndian = true) { _ = CommonReadValue(out ReadOnlyMemory value, expectedTag, FixedLengthInt32, true); - if (bigEndian == true) + if (bigEndian) { return BinaryPrimitives.ReadInt32BigEndian(value.Span); } @@ -763,9 +763,9 @@ public bool TryReadInt32(out int value, int expectedTag, bool bigEndian = true) FixedLengthInt32, false); - if (isValid == true) + if (isValid) { - if (bigEndian == true) + if (bigEndian) { value = BinaryPrimitives.ReadInt32BigEndian(fullValue.Span); } @@ -1108,38 +1108,57 @@ private bool CommonReadValue( int fixedLength, bool throwIfFailed) { - value = Memory.Empty; - - int result = ReadTagExpected(expectedTag); - if (result != ValidEncoding) + bool isValidTlv = IsValidTlv(expectedTag, fixedLength, out int resultCode); + if (isValidTlv) { - goto exit; + value = _encoding.Slice(_currentValueOffset, _currentLength); + _currentOffset = _currentValueOffset + _currentLength; + + ResetState(); + return true; } - result = ReadLength(); - if (result != ValidEncoding) + // We must reset the state before we throw or return as well, so ResetState() is duplicated but the + // intent is more clear that we need to reset the state in all (3) cases. + ResetState(); + if (throwIfFailed) { - goto exit; + ThrowOnFailedRead(resultCode); } - result = VerifyValue(fixedLength); - if (result != ValidEncoding) + value = Memory.Empty; + return false; + } + + /// + /// Attempts to read and validate the expected tag, its length, and its value, indicating success through the return value and providing a result code. + /// + /// The tag expected to be read. + /// The fixed length that the value is expected to adhere to. + /// Out parameter that returns the result code of the operation, indicating the specific outcome or error. + /// Returns true if the tag, length, and value are successfully read and validated. Returns false if any validation fails, along with the appropriate result code. + private bool IsValidTlv(int expectedTag, int fixedLength, out int resultCode) + { + resultCode = ReadTagExpected(expectedTag); + if (resultCode != ValidEncoding) { - goto exit; + return false; } - value = _encoding.Slice(_currentValueOffset, _currentLength); - _currentOffset = _currentValueOffset + _currentLength; - -exit: - ResetState(); + resultCode = ReadLength(); + if (resultCode != ValidEncoding) + { + return false; + } - if ((result != ValidEncoding) && (throwIfFailed == true)) + resultCode = VerifyValue(fixedLength); + if (resultCode != ValidEncoding) { - ThrowOnFailedRead(result); + return false; } - return result == ValidEncoding; + // Valid Tlv, we were able to read the tag, length and verify the value + return true; } // Read the tag, verifying the tag in the encoding is the same as the @@ -1168,9 +1187,9 @@ private int ReadTagExpected(int expectedTag) } int result = ReadTag(tagLength); - if ((result == ValidEncoding) && (_currentTag != expectedTag)) + if (result == ValidEncoding && _currentTag != expectedTag) { - result = UnexpectedEncoding; + return UnexpectedEncoding; } return result; @@ -1184,7 +1203,7 @@ private int ReadTagExpected(int expectedTag) // UnexpectedEnd (not enough bytes to read) private int ReadTag(int tagLength) { - if ((tagLength <= 0) || (tagLength > MaximumTagLength)) + if (tagLength <= 0 || tagLength > MaximumTagLength) { return UnsupportedTag; } @@ -1196,7 +1215,7 @@ private int ReadTag(int tagLength) ResetState(); - if ((_currentOffset + tagLength) > _encoding.Length) + if (_currentOffset + tagLength > _encoding.Length) { return UnexpectedEnd; } @@ -1228,7 +1247,7 @@ private int ReadLength() } int count = 1; - if ((_currentOffset + _currentTagLength) < _encoding.Length) + if (_currentOffset + _currentTagLength < _encoding.Length) { _currentLength = (int)_encoding.Span[_currentOffset + _currentTagLength]; if (_currentLength <= 0x7F) @@ -1244,11 +1263,11 @@ private int ReadLength() // If the initial length byte is 0x80, that is an unsupported value // (it's BER for indefinite length and we support DER only). In that // case, we would have set count to 0 (0x80 & 0x7F yields 0). - if ((count == 0) || (count > MaximumLengthCount)) + if (count == 0 || count > MaximumLengthCount) { return UnsupportedLength; } - if ((_currentOffset + _currentTagLength + count + 1) > _encoding.Length) + if (_currentOffset + _currentTagLength + count + 1 > _encoding.Length) { return UnexpectedEnd; } @@ -1289,7 +1308,7 @@ private int VerifyValue(int fixedLength) break; } - return (_currentValueOffset + _currentLength) <= _encoding.Length + return _currentValueOffset + _currentLength <= _encoding.Length ? ValidEncoding : UnexpectedEnd; } diff --git a/Yubico.Core/src/Yubico/Core/Tlv/TlvSubElement.cs b/Yubico.Core/src/Yubico/Core/Tlv/TlvSubElement.cs index ff212c5c..86da0e77 100644 --- a/Yubico.Core/src/Yubico/Core/Tlv/TlvSubElement.cs +++ b/Yubico.Core/src/Yubico/Core/Tlv/TlvSubElement.cs @@ -70,7 +70,7 @@ public TlvSubElement(int tag, ReadOnlySpan value) _tagAndLength = BuildTagAndLength(tag, value.Length); _value = value.ToArray(); - _encodedLength = _tagAndLength.Length + _value.Length; + _encodedLength = _tagAndLength.Length + _value.Length; } /// @@ -97,7 +97,7 @@ public TlvSubElement(ReadOnlySpan encodedTlv) override public bool TryEncode(Span encoding, int offset, out int bytesWritten) { bytesWritten = 0; - if (encoding.Length < (offset + _encodedLength)) + if (encoding.Length < offset + _encodedLength) { return false; } diff --git a/Yubico.Core/src/Yubico/Core/Tlv/TlvWriter.cs b/Yubico.Core/src/Yubico/Core/Tlv/TlvWriter.cs index 57ff262d..e12cbbf5 100644 --- a/Yubico.Core/src/Yubico/Core/Tlv/TlvWriter.cs +++ b/Yubico.Core/src/Yubico/Core/Tlv/TlvWriter.cs @@ -13,8 +13,8 @@ // limitations under the License. using System; -using System.Collections.Generic; using System.Buffers.Binary; +using System.Collections.Generic; using System.Text; namespace Yubico.Core.Tlv @@ -126,6 +126,7 @@ private void EndNestedTlv() { throw new TlvException(ExceptionMessages.TlvInvalidSchema); } + TlvNestedTlv nestedToEnd = _nestedTlvStack.Pop(); TlvNestedTlv parent = _nestedTlvStack.Peek(); parent.AddSubElement(nestedToEnd); @@ -254,6 +255,7 @@ public void WriteString(int tag, string value, Encoding encoding) { throw new ArgumentNullException(nameof(encoding)); } + WriteValue(tag, encoding.GetBytes(value)); } @@ -299,7 +301,8 @@ public void WriteByte(int tag, byte value) public void WriteInt16(int tag, short value, bool bigEndian = true) { byte[] valueArray = new byte[2]; - if (bigEndian == true) + + if (bigEndian) { BinaryPrimitives.WriteInt16BigEndian(valueArray, value); } @@ -330,7 +333,8 @@ public void WriteInt16(int tag, short value, bool bigEndian = true) public void WriteUInt16(int tag, ushort value, bool bigEndian = true) { byte[] valueArray = new byte[2]; - if (bigEndian == true) + + if (bigEndian) { BinaryPrimitives.WriteUInt16BigEndian(valueArray, value); } @@ -363,7 +367,8 @@ public void WriteUInt16(int tag, ushort value, bool bigEndian = true) public void WriteInt32(int tag, int value, bool bigEndian = true) { byte[] valueArray = new byte[4]; - if (bigEndian == true) + + if (bigEndian) { BinaryPrimitives.WriteInt32BigEndian(valueArray, value); } @@ -420,6 +425,7 @@ public byte[] Encode() TlvNestedTlv initialNested = GetInitialNestedTlv(); byte[] encoding = new byte[initialNested.EncodedLength]; + if (initialNested.TryEncode(encoding, 0, out _) == false) { throw new TlvException(ExceptionMessages.TlvInvalidSchema); @@ -561,6 +567,7 @@ private TlvNestedTlv GetInitialNestedTlv() /// /// /// + // // When we're following a schema, we want to make sure the elements that // belong under a particular NestedTlv are placed there and not anywhere @@ -632,7 +639,7 @@ private TlvNestedTlv GetInitialNestedTlv() // method and allow the using construction. Hence, there is no need to // compare instances. We could have made this a Class instead of a // Struct, but we are following the AsnWriter pattern. -#pragma warning disable CA1034, CA1815 // see comments above +#pragma warning disable CA1034, CA1815 // see comments above public struct TlvScope : IDisposable { private TlvWriter? _writer; @@ -655,6 +662,7 @@ internal TlvScope(TlvWriter writer) /// will make sure the Nested TLV is ended and any new additions to the /// TlvWriter object will be associated with the Nested TLV's parent. /// + // Note that .NET recommends a Dispose method call Dispose(true) and // GC.SuppressFinalize(this). The actual disposal is in the // Dispose(bool) method. diff --git a/Yubico.Core/src/Yubico/PlatformInterop/Desktop/SCard/SCardCardHandle.cs b/Yubico.Core/src/Yubico/PlatformInterop/Desktop/SCard/SCardCardHandle.cs index 6136ff4d..3f48cee4 100644 --- a/Yubico.Core/src/Yubico/PlatformInterop/Desktop/SCard/SCardCardHandle.cs +++ b/Yubico.Core/src/Yubico/PlatformInterop/Desktop/SCard/SCardCardHandle.cs @@ -12,10 +12,9 @@ // See the License for the specific language governing permissions and // limitations under the License. -using Microsoft.Win32.SafeHandles; using System; using System.Runtime.ConstrainedExecution; - +using Microsoft.Win32.SafeHandles; using static Yubico.PlatformInterop.NativeMethods; namespace Yubico.PlatformInterop diff --git a/Yubico.Core/src/Yubico/PlatformInterop/Desktop/SCard/SCardContext.cs b/Yubico.Core/src/Yubico/PlatformInterop/Desktop/SCard/SCardContext.cs index 51a8c91a..6df6ef73 100644 --- a/Yubico.Core/src/Yubico/PlatformInterop/Desktop/SCard/SCardContext.cs +++ b/Yubico.Core/src/Yubico/PlatformInterop/Desktop/SCard/SCardContext.cs @@ -12,9 +12,9 @@ // See the License for the specific language governing permissions and // limitations under the License. -using Microsoft.Win32.SafeHandles; using System; using System.Runtime.ConstrainedExecution; +using Microsoft.Win32.SafeHandles; namespace Yubico.PlatformInterop { diff --git a/Yubico.Core/src/Yubico/PlatformInterop/Linux/Libc/Libc.Interop.cs b/Yubico.Core/src/Yubico/PlatformInterop/Linux/Libc/Libc.Interop.cs index c6feccf3..8354534c 100644 --- a/Yubico.Core/src/Yubico/PlatformInterop/Linux/Libc/Libc.Interop.cs +++ b/Yubico.Core/src/Yubico/PlatformInterop/Linux/Libc/Libc.Interop.cs @@ -95,18 +95,17 @@ public enum OpenFlags // Read count bytes. Place them into outputBuffer. [DllImport(Libraries.LinuxKernelLib, CharSet = CharSet.Ansi, EntryPoint = "read", SetLastError = true)] [DefaultDllImportSearchPaths(DllImportSearchPath.SafeDirectories)] - public static extern int read( - LinuxFileSafeHandle handle, - [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] byte[] outputBuffer, - int count); + public static extern int read(LinuxFileSafeHandle handle, + [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] + byte[] outputBuffer, + int count); // Write the count bytes in inputBuffer. [DllImport(Libraries.LinuxKernelLib, CharSet = CharSet.Ansi, EntryPoint = "write", SetLastError = true)] [DefaultDllImportSearchPaths(DllImportSearchPath.SafeDirectories)] - public static extern int write( - int handle, - [MarshalAs(UnmanagedType.LPArray)] byte[] inputBuffer, - int count); + public static extern int write(int handle, + [MarshalAs(UnmanagedType.LPArray)] byte[] inputBuffer, + int count); [DllImport(Libraries.LinuxKernelLib, CharSet = CharSet.Ansi, EntryPoint = "fcntl", SetLastError = true)] [DefaultDllImportSearchPaths(DllImportSearchPath.SafeDirectories)] diff --git a/Yubico.Core/src/Yubico/PlatformInterop/Linux/Libc/LinuxFileSafeHandle.cs b/Yubico.Core/src/Yubico/PlatformInterop/Linux/Libc/LinuxFileSafeHandle.cs index 15a91a53..98d8b268 100644 --- a/Yubico.Core/src/Yubico/PlatformInterop/Linux/Libc/LinuxFileSafeHandle.cs +++ b/Yubico.Core/src/Yubico/PlatformInterop/Linux/Libc/LinuxFileSafeHandle.cs @@ -13,8 +13,8 @@ // limitations under the License. using System; -using System.Runtime.InteropServices; using System.Runtime.ConstrainedExecution; +using System.Runtime.InteropServices; namespace Yubico.PlatformInterop { diff --git a/Yubico.Core/src/Yubico/PlatformInterop/Linux/Udev/LinuxUdevDeviceSafeHandle.cs b/Yubico.Core/src/Yubico/PlatformInterop/Linux/Udev/LinuxUdevDeviceSafeHandle.cs index 5c55f2de..7096eafa 100644 --- a/Yubico.Core/src/Yubico/PlatformInterop/Linux/Udev/LinuxUdevDeviceSafeHandle.cs +++ b/Yubico.Core/src/Yubico/PlatformInterop/Linux/Udev/LinuxUdevDeviceSafeHandle.cs @@ -13,8 +13,8 @@ // limitations under the License. using System; -using System.Runtime.InteropServices; using System.Runtime.ConstrainedExecution; +using System.Runtime.InteropServices; namespace Yubico.PlatformInterop { diff --git a/Yubico.Core/src/Yubico/PlatformInterop/Linux/Udev/LinuxUdevEnumerateSafeHandle.cs b/Yubico.Core/src/Yubico/PlatformInterop/Linux/Udev/LinuxUdevEnumerateSafeHandle.cs index c05938d3..58060a45 100644 --- a/Yubico.Core/src/Yubico/PlatformInterop/Linux/Udev/LinuxUdevEnumerateSafeHandle.cs +++ b/Yubico.Core/src/Yubico/PlatformInterop/Linux/Udev/LinuxUdevEnumerateSafeHandle.cs @@ -13,8 +13,8 @@ // limitations under the License. using System; -using System.Runtime.InteropServices; using System.Runtime.ConstrainedExecution; +using System.Runtime.InteropServices; namespace Yubico.PlatformInterop { diff --git a/Yubico.Core/src/Yubico/PlatformInterop/Linux/Udev/LinuxUdevMonitorSafeHandle.cs b/Yubico.Core/src/Yubico/PlatformInterop/Linux/Udev/LinuxUdevMonitorSafeHandle.cs index 061ae96a..71cc97f0 100644 --- a/Yubico.Core/src/Yubico/PlatformInterop/Linux/Udev/LinuxUdevMonitorSafeHandle.cs +++ b/Yubico.Core/src/Yubico/PlatformInterop/Linux/Udev/LinuxUdevMonitorSafeHandle.cs @@ -13,8 +13,8 @@ // limitations under the License. using System; -using System.Runtime.InteropServices; using System.Runtime.ConstrainedExecution; +using System.Runtime.InteropServices; namespace Yubico.PlatformInterop { diff --git a/Yubico.Core/src/Yubico/PlatformInterop/Linux/Udev/LinuxUdevSafeHandle.cs b/Yubico.Core/src/Yubico/PlatformInterop/Linux/Udev/LinuxUdevSafeHandle.cs index cdf9643d..11a9920f 100644 --- a/Yubico.Core/src/Yubico/PlatformInterop/Linux/Udev/LinuxUdevSafeHandle.cs +++ b/Yubico.Core/src/Yubico/PlatformInterop/Linux/Udev/LinuxUdevSafeHandle.cs @@ -13,8 +13,8 @@ // limitations under the License. using System; -using System.Runtime.InteropServices; using System.Runtime.ConstrainedExecution; +using System.Runtime.InteropServices; namespace Yubico.PlatformInterop { diff --git a/Yubico.Core/src/Yubico/PlatformInterop/Linux/Udev/LinuxUdevScan.cs b/Yubico.Core/src/Yubico/PlatformInterop/Linux/Udev/LinuxUdevScan.cs index d7f20ce6..1dd35eeb 100644 --- a/Yubico.Core/src/Yubico/PlatformInterop/Linux/Udev/LinuxUdevScan.cs +++ b/Yubico.Core/src/Yubico/PlatformInterop/Linux/Udev/LinuxUdevScan.cs @@ -13,9 +13,9 @@ // limitations under the License. using System; -using System.Text; using System.Collections.Generic; using System.Runtime.InteropServices; +using System.Text; using Yubico.Core.Devices.Hid; namespace Yubico.PlatformInterop diff --git a/Yubico.Core/src/Yubico/PlatformInterop/Linux/Udev/Udev.Interop.cs b/Yubico.Core/src/Yubico/PlatformInterop/Linux/Udev/Udev.Interop.cs index 2b0bdadf..825488d0 100644 --- a/Yubico.Core/src/Yubico/PlatformInterop/Linux/Udev/Udev.Interop.cs +++ b/Yubico.Core/src/Yubico/PlatformInterop/Linux/Udev/Udev.Interop.cs @@ -259,13 +259,13 @@ public static extern int udev_monitor_filter_add_match_subsystem_devtype( // struct udev_device *udev_monitor_receive_device(struct udev_monitor *udev_monitor); [DllImport(Libraries.LinuxUdevLib, CharSet = CharSet.Ansi, EntryPoint = "udev_monitor_receive_device", SetLastError = true)] [DefaultDllImportSearchPaths(DllImportSearchPath.SafeDirectories)] - public static extern LinuxUdevDeviceSafeHandle udev_monitor_receive_device (LinuxUdevMonitorSafeHandle monitorObject); - + public static extern LinuxUdevDeviceSafeHandle udev_monitor_receive_device(LinuxUdevMonitorSafeHandle monitorObject); + // Get the socket file descriptor associated with the monitor. // The C signature is // int udev_monitor_get_fd(struct udev_monitor *udev_monitor); [DllImport(Libraries.LinuxUdevLib, CharSet = CharSet.Ansi, EntryPoint = "udev_monitor_get_fd", SetLastError = true)] [DefaultDllImportSearchPaths(DllImportSearchPath.SafeDirectories)] - public static extern IntPtr udev_monitor_get_fd (LinuxUdevMonitorSafeHandle monitorObject); + public static extern IntPtr udev_monitor_get_fd(LinuxUdevMonitorSafeHandle monitorObject); } } diff --git a/Yubico.Core/src/Yubico/PlatformInterop/SdkPlatformInfo.cs b/Yubico.Core/src/Yubico/PlatformInterop/SdkPlatformInfo.cs index 4b71a02c..78237ee7 100644 --- a/Yubico.Core/src/Yubico/PlatformInterop/SdkPlatformInfo.cs +++ b/Yubico.Core/src/Yubico/PlatformInterop/SdkPlatformInfo.cs @@ -14,8 +14,8 @@ using System; using System.Runtime.InteropServices; -using System.Text; using System.Security.Principal; +using System.Text; namespace Yubico.PlatformInterop { diff --git a/Yubico.Core/src/Yubico/PlatformInterop/Windows/Cfgmgr32/CmDevice.cs b/Yubico.Core/src/Yubico/PlatformInterop/Windows/Cfgmgr32/CmDevice.cs index e392e198..22244218 100644 --- a/Yubico.Core/src/Yubico/PlatformInterop/Windows/Cfgmgr32/CmDevice.cs +++ b/Yubico.Core/src/Yubico/PlatformInterop/Windows/Cfgmgr32/CmDevice.cs @@ -12,13 +12,13 @@ // See the License for the specific language governing permissions and // limitations under the License. -using Microsoft.Win32.SafeHandles; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Runtime.InteropServices; +using Microsoft.Win32.SafeHandles; using Yubico.Core.Buffers; using static Yubico.PlatformInterop.NativeMethods; diff --git a/Yubico.Core/src/Yubico/PlatformInterop/Windows/HidD/HidD.Interop.cs b/Yubico.Core/src/Yubico/PlatformInterop/Windows/HidD/HidD.Interop.cs index cf307810..40f37172 100644 --- a/Yubico.Core/src/Yubico/PlatformInterop/Windows/HidD/HidD.Interop.cs +++ b/Yubico.Core/src/Yubico/PlatformInterop/Windows/HidD/HidD.Interop.cs @@ -12,9 +12,9 @@ // See the License for the specific language governing permissions and // limitations under the License. -using Microsoft.Win32.SafeHandles; using System; using System.Runtime.InteropServices; +using Microsoft.Win32.SafeHandles; namespace Yubico.PlatformInterop { diff --git a/Yubico.Core/src/Yubico/PlatformInterop/Windows/HidD/HidDDevice.cs b/Yubico.Core/src/Yubico/PlatformInterop/Windows/HidD/HidDDevice.cs index f161ba32..052a6485 100644 --- a/Yubico.Core/src/Yubico/PlatformInterop/Windows/HidD/HidDDevice.cs +++ b/Yubico.Core/src/Yubico/PlatformInterop/Windows/HidD/HidDDevice.cs @@ -12,9 +12,9 @@ // See the License for the specific language governing permissions and // limitations under the License. -using Microsoft.Win32.SafeHandles; using System; using System.Runtime.InteropServices; +using Microsoft.Win32.SafeHandles; using Yubico.Core; using static Yubico.PlatformInterop.NativeMethods; diff --git a/Yubico.Core/src/Yubico/PlatformInterop/Windows/Kernel32/Kernel32.Interop.cs b/Yubico.Core/src/Yubico/PlatformInterop/Windows/Kernel32/Kernel32.Interop.cs index 2253c6ce..368cdbd4 100644 --- a/Yubico.Core/src/Yubico/PlatformInterop/Windows/Kernel32/Kernel32.Interop.cs +++ b/Yubico.Core/src/Yubico/PlatformInterop/Windows/Kernel32/Kernel32.Interop.cs @@ -12,9 +12,9 @@ // See the License for the specific language governing permissions and // limitations under the License. -using Microsoft.Win32.SafeHandles; using System; using System.Runtime.InteropServices; +using Microsoft.Win32.SafeHandles; namespace Yubico.PlatformInterop { diff --git a/Yubico.Core/tests/Yubico.Core.UnitTests.csproj b/Yubico.Core/tests/Yubico.Core.UnitTests.csproj index c07faf01..03350dab 100644 --- a/Yubico.Core/tests/Yubico.Core.UnitTests.csproj +++ b/Yubico.Core/tests/Yubico.Core.UnitTests.csproj @@ -44,9 +44,9 @@ limitations under the License. --> - - - + + + diff --git a/Yubico.Core/tests/Yubico/Core/Cryptography/BnTests.cs b/Yubico.Core/tests/Yubico/Core/Cryptography/BnTests.cs index 3792340d..45cd24d3 100644 --- a/Yubico.Core/tests/Yubico/Core/Cryptography/BnTests.cs +++ b/Yubico.Core/tests/Yubico/Core/Cryptography/BnTests.cs @@ -12,8 +12,8 @@ // See the License for the specific language governing permissions and // limitations under the License. -using Yubico.PlatformInterop; using Xunit; +using Yubico.PlatformInterop; namespace Yubico.Core.Cryptography { diff --git a/Yubico.Core/tests/Yubico/Core/Devices/Hid/HidConnectionTests.cs b/Yubico.Core/tests/Yubico/Core/Devices/Hid/HidConnectionTests.cs index 1830a8aa..ce007f7f 100644 --- a/Yubico.Core/tests/Yubico/Core/Devices/Hid/HidConnectionTests.cs +++ b/Yubico.Core/tests/Yubico/Core/Devices/Hid/HidConnectionTests.cs @@ -12,16 +12,16 @@ // See the License for the specific language governing permissions and // limitations under the License. -using Moq; using System; using System.Linq; +using Moq; using Xunit; using Yubico.Core.Buffers; using Yubico.PlatformInterop; namespace Yubico.Core.Devices.Hid.UnitTests { - + #if false public class HidConnectionTests { diff --git a/Yubico.Core/tests/Yubico/Core/Devices/Hid/HidDeviceListenerTests.cs b/Yubico.Core/tests/Yubico/Core/Devices/Hid/HidDeviceListenerTests.cs index ec219cc2..4f2526c6 100644 --- a/Yubico.Core/tests/Yubico/Core/Devices/Hid/HidDeviceListenerTests.cs +++ b/Yubico.Core/tests/Yubico/Core/Devices/Hid/HidDeviceListenerTests.cs @@ -20,7 +20,7 @@ namespace Yubico.Core.Devices.Hid.UnitTests class FakeHidDevice : IHidDevice { public DateTime LastAccessed { get; } = DateTime.Now; - public string Path { get; } = String.Empty; + public string Path { get; } = string.Empty; public string? ParentDeviceId { get; } = null; public short VendorId { get; } public short ProductId { get; } @@ -43,7 +43,7 @@ public class HidDeviceListenerTests public void Create_ReturnsInstanceOfListener() { var listener = HidDeviceListener.Create(); - Assert.IsAssignableFrom(listener); + _ = Assert.IsAssignableFrom(listener); } [Fact] @@ -57,7 +57,7 @@ public void OnArrived_WithNoListeners_NoOps() public void OnArrived_WithEventListener_RaisesArrivedEvent() { var listener = new FakeHidListener(); - Assert.Raises( + _ = Assert.Raises( e => listener.Arrived += e, e => listener.Arrived -= e, () => listener.FireArrival()); @@ -74,7 +74,7 @@ public void OnRemoved_WithNoListeners_NoOps() public void OnRemoved_WithEventListener_RaisesRemovedEvent() { var listener = new FakeHidListener(); - Assert.Raises( + _ = Assert.Raises( e => listener.Removed += e, e => listener.Removed -= e, () => listener.FireRemoval()); diff --git a/Yubico.Core/tests/Yubico/Core/Devices/Hid/HidTranslatorTests.cs b/Yubico.Core/tests/Yubico/Core/Devices/Hid/HidTranslatorTests.cs index a31bb99e..32616a6d 100644 --- a/Yubico.Core/tests/Yubico/Core/Devices/Hid/HidTranslatorTests.cs +++ b/Yubico.Core/tests/Yubico/Core/Devices/Hid/HidTranslatorTests.cs @@ -206,10 +206,10 @@ private static (char, byte)[] GetDataForKeyboard(KeyboardLayout layout) -1 => $"ToAscii returned -1 converting scan code to a char, which means that it is a dead key (https://bit.ly/3tZOIi0).", 0 => $"ToAscii returned 0 converting scan code to a char, which means that there is no mapping for the current code.", 2 => $"ToAscii returned 2, which means that a dead key (https://bit.ly/3tZOIi0) had state in the keyboard state buffer. Should never happen here.", - _ => $"ToAscii returned { result }. This is not a documented return value for ToAscii." + _ => $"ToAscii returned {result}. This is not a documented return value for ToAscii." }; string message = error + Environment.NewLine + - $"HID Usage Code[{ code.ToString("x2") }], PS/2 Scan Code[{ scanCode.ToString("x2") }], VKey[{ vkey.ToString("x2") }]"; + $"HID Usage Code[{code.ToString("x2")}], PS/2 Scan Code[{scanCode.ToString("x2")}], VKey[{vkey.ToString("x2")}]"; throw new InvalidOperationException(message); } // Windows returns \r for the enter key, so we'll just swap. @@ -285,7 +285,7 @@ private static IntPtr GetKeyboardLayout(KeyboardLayout layout) => KeyboardLayout.sv_SE => NativeMethods.LoadKeyboardLayout("0000410d", 0), // We'll use the en_US layout for ModHex. KeyboardLayout.ModHex => NativeMethods.LoadKeyboardLayout("00000409", 0), - _ => throw new NotSupportedException($"Layout [{ layout }] not implemented." + _ => throw new NotSupportedException($"Layout [{layout}] not implemented." + Environment.NewLine + "Did you implement a new layout without adding it here?") }; diff --git a/Yubico.Core/tests/Yubico/Core/Iso7816/CommandApduTests.cs b/Yubico.Core/tests/Yubico/Core/Iso7816/CommandApduTests.cs index 0cc9b7ff..5464027a 100644 --- a/Yubico.Core/tests/Yubico/Core/Iso7816/CommandApduTests.cs +++ b/Yubico.Core/tests/Yubico/Core/Iso7816/CommandApduTests.cs @@ -26,8 +26,8 @@ public class CommandApduTests private static readonly byte[] _header = new byte[] { 0xBA, 0xDF, 0x00, 0xD }; private static byte _cla => _header[0]; private static byte _ins => _header[1]; - private static byte _p1 => _header[2]; - private static byte _p2 => _header[3]; + private static byte _p1 => _header[2]; + private static byte _p2 => _header[3]; // // Private utility functions @@ -577,11 +577,11 @@ public void AsEncodingByteArray_NeSetIntMaxValue_EmitsCorrectApduMaxNe(ApduEncod { int ne = int.MaxValue; byte[] expectedLe = apduEncoding switch - { - ApduEncoding.ShortLength => new byte[] { 0x00 }, - ApduEncoding.ExtendedLength => new byte[] { 0x00, 0x00, 0x00 }, - _ => Array.Empty(), // Shouldn't be reached - }; + { + ApduEncoding.ShortLength => new byte[] { 0x00 }, + ApduEncoding.ExtendedLength => new byte[] { 0x00, 0x00, 0x00 }, + _ => Array.Empty(), // Shouldn't be reached + }; var expectedByteArray = new List(); expectedByteArray.AddRange(_header); diff --git a/Yubico.Core/tests/Yubico/Core/Tlv/TlvReaderTests.cs b/Yubico.Core/tests/Yubico/Core/Tlv/TlvReaderTests.cs index b49a7465..1969c453 100644 --- a/Yubico.Core/tests/Yubico/Core/Tlv/TlvReaderTests.cs +++ b/Yubico.Core/tests/Yubico/Core/Tlv/TlvReaderTests.cs @@ -13,8 +13,8 @@ // limitations under the License. using System; -using System.Text; using System.Linq; +using System.Text; using Xunit; namespace Yubico.Core.Tlv.UnitTests @@ -296,7 +296,7 @@ public void ReadInt32_ReturnsCorrect(int value, bool bigEndian) { byte value0 = (byte)(value >> 24); byte value1 = (byte)(value >> 16); - byte value2 = (byte)(value >> 8); + byte value2 = (byte)(value >> 8); byte value3 = (byte)value; byte[] encoding = new byte[] { 0x01, 0x04, value0, value1, value2, value3 }; if (bigEndian == false) diff --git a/Yubico.Core/tests/Yubico/Core/Tlv/TlvTryTests.cs b/Yubico.Core/tests/Yubico/Core/Tlv/TlvTryTests.cs index 8438c8c5..a5c240b7 100644 --- a/Yubico.Core/tests/Yubico/Core/Tlv/TlvTryTests.cs +++ b/Yubico.Core/tests/Yubico/Core/Tlv/TlvTryTests.cs @@ -15,7 +15,6 @@ using System; using System.Security.Cryptography; using Xunit; -using Yubico.Core.Tlv; namespace Yubico.Core.Tlv.UnitTests { @@ -24,7 +23,8 @@ public class TlvTryTests [Fact] public void Tlv_TryReadValue() { - byte[] encoding = new byte[] { + byte[] encoding = new byte[] + { 0x02, 0x05, 0x31, 0x32, 0x33, 0x34, 0x35 }; @@ -58,18 +58,19 @@ public void Tlv_TryReadValue_ReturnsCorrectValue() [Fact] public void Tlv_TryReadNested() { - byte[] encoding = new byte[] { + byte[] encoding = new byte[] + { 0x72, 0x61, 0x0A, - 0x01, 0x02, 0x41, 0x42, - 0x02, 0x04, 0x31, 0x32, 0x33, 0x34 + 0x01, 0x02, 0x41, 0x42, + 0x02, 0x04, 0x31, 0x32, 0x33, 0x34 }; var reader = new TlvReader(encoding); bool validRead = reader.TryReadNestedTlv(out TlvReader nested, 0x7261); - if (validRead == true) + if (validRead) { validRead = nested.TryReadValue(out ReadOnlyMemory value, 0x01); - if (validRead == true) + if (validRead) { Assert.Equal(2, value.Length); validRead = nested.TryReadValue(out value, 0x02); @@ -111,7 +112,7 @@ public void Tlv_TryReadInt16_LittleEndian() var reader = new TlvReader(encoding); bool validRead = reader.TryReadInt16(out short value, 0xFF); - if (validRead == true) + if (validRead) { validRead = reader.TryReadInt16(out value, 0xFE, false); } @@ -139,7 +140,7 @@ public void Tlv_TryReadUInt16_LittleEndian() var reader = new TlvReader(encoding); bool validRead = reader.TryReadUInt16(out ushort value, 0xFF); - if (validRead == true) + if (validRead) { validRead = reader.TryReadUInt16(out value, 0xFE, false); } @@ -176,7 +177,8 @@ public void Tlv_TryReadInt32_LittleEndian() public void Tlv_TryReadString() { string expectedValue = "12345"; - byte[] encoding = new byte[] { + byte[] encoding = new byte[] + { 0x02, 0x05, 0x31, 0x32, 0x33, 0x34, 0x35 }; @@ -190,25 +192,25 @@ public void Tlv_TryReadString() [Fact] public void TlvTryRead_MultipleValues_Correct() { - byte[] encoding = new byte[] { + byte[] encoding = new byte[] + { 0x72, 0x61, 0x0A, - 0x01, 0x02, 0x41, 0x42, - 0x02, 0x04, 0x31, 0x32, 0x33, 0x34 + 0x01, 0x02, 0x41, 0x42, + 0x02, 0x04, 0x31, 0x32, 0x33, 0x34 }; var reader = new TlvReader(encoding); bool validRead = reader.TryReadNestedTlv(out TlvReader nested, 0x7261); - if (validRead == true) + if (validRead) { - validRead = nested.TryReadValue(out ReadOnlyMemory value, 0x91); + validRead = nested.TryReadValue(out _, 0x91); Assert.False(validRead); - - validRead = nested.TryReadValue(out value, 0x01); - if (validRead == true) + validRead = nested.TryReadValue(out ReadOnlyMemory value, 0x01); + if (validRead) { Assert.Equal(2, value.Length); - validRead = nested.TryReadValue(out value, 0x92); + validRead = nested.TryReadValue(out _, 0x92); Assert.False(validRead); validRead = nested.TryReadValue(out value, 0x02); @@ -245,13 +247,14 @@ public void TryReadValue_TwoByteLength() [Fact] public void TryReadNested_WrongTag_ReturnsFalse() { - byte[] encoding = new byte[] { + byte[] encoding = new byte[] + { 0x81, 0x13, - 0x01, 0x02, 0x31, 0x32, - 0x82, 0x0B, - 0x03, 0x02, 0x41, 0x42, - 0x04, 0x05, 0x61, 0x62, 0x63, 0x64, 0x65, - 0x91, 0x00 + 0x01, 0x02, 0x31, 0x32, + 0x82, 0x0B, + 0x03, 0x02, 0x41, 0x42, + 0x04, 0x05, 0x61, 0x62, 0x63, 0x64, 0x65, + 0x91, 0x00 }; var reader = new TlvReader(encoding); @@ -271,11 +274,12 @@ public void TryReadNested_WrongTag_ReturnsFalse() [Fact] public void TryReadValue_WrongTag_ReturnsFalse() { - byte[] encoding = new byte[] { + byte[] encoding = new byte[] + { 0x81, 0x13, - 0x11, 0x08, 0x31, 0x32, 0x82, 0x0B, 0x03, 0x02, 0x41, 0x42, - 0x04, 0x05, 0x61, 0x62, 0x63, 0x64, 0x65, - 0x91, 0x00 + 0x11, 0x08, 0x31, 0x32, 0x82, 0x0B, 0x03, 0x02, 0x41, 0x42, + 0x04, 0x05, 0x61, 0x62, 0x63, 0x64, 0x65, + 0x91, 0x00 }; var reader = new TlvReader(encoding); @@ -291,11 +295,12 @@ public void TryReadValue_WrongTag_ReturnsFalse() [Fact] public void TryReadValue_InvalidLength_ReturnsFalse() { - byte[] encoding = new byte[] { + byte[] encoding = new byte[] + { 0x81, 0x13, - 0x11, 0x80, 0x31, 0x32, 0x82, 0x0B, 0x03, 0x02, 0x41, 0x42, - 0x04, 0x05, 0x61, 0x62, 0x63, 0x64, 0x65, - 0x91, 0x00 + 0x11, 0x80, 0x31, 0x32, 0x82, 0x0B, 0x03, 0x02, 0x41, 0x42, + 0x04, 0x05, 0x61, 0x62, 0x63, 0x64, 0x65, + 0x91, 0x00 }; var reader = new TlvReader(encoding); @@ -311,11 +316,12 @@ public void TryReadValue_InvalidLength_ReturnsFalse() [Fact] public void TryReadValue_NotEnoughData_ReturnsFalse() { - byte[] encoding = new byte[] { + byte[] encoding = new byte[] + { 0x81, 0x13, - 0x11, 0x12, 0x31, 0x32, 0x82, 0x0B, 0x03, 0x02, 0x41, 0x42, - 0x04, 0x05, 0x61, 0x62, 0x63, 0x64, 0x65, - 0x91, 0x00 + 0x11, 0x12, 0x31, 0x32, 0x82, 0x0B, 0x03, 0x02, 0x41, 0x42, + 0x04, 0x05, 0x61, 0x62, 0x63, 0x64, 0x65, + 0x91, 0x00 }; var reader = new TlvReader(encoding); @@ -331,11 +337,12 @@ public void TryReadValue_NotEnoughData_ReturnsFalse() [Fact] public void TryReadByte_LengthZero_ReturnsFalse() { - byte[] encoding = new byte[] { + byte[] encoding = new byte[] + { 0x81, 0x13, - 0x91, 0x00, - 0x11, 0x08, 0x31, 0x32, 0x82, 0x0B, 0x03, 0x02, 0x41, 0x42, - 0x04, 0x05, 0x61, 0x62, 0x63, 0x64, 0x65 + 0x91, 0x00, + 0x11, 0x08, 0x31, 0x32, 0x82, 0x0B, 0x03, 0x02, 0x41, 0x42, + 0x04, 0x05, 0x61, 0x62, 0x63, 0x64, 0x65 }; var reader = new TlvReader(encoding); @@ -351,11 +358,12 @@ public void TryReadByte_LengthZero_ReturnsFalse() [Fact] public void TryReadByte_LengthTwo_ReturnsFalse() { - byte[] encoding = new byte[] { + byte[] encoding = new byte[] + { 0x81, 0x15, - 0x91, 0x02, 0x41, 0x42, - 0x11, 0x08, 0x31, 0x32, 0x82, 0x0B, 0x03, 0x02, 0x41, 0x42, - 0x04, 0x05, 0x61, 0x62, 0x63, 0x64, 0x65, + 0x91, 0x02, 0x41, 0x42, + 0x11, 0x08, 0x31, 0x32, 0x82, 0x0B, 0x03, 0x02, 0x41, 0x42, + 0x04, 0x05, 0x61, 0x62, 0x63, 0x64, 0x65, }; var reader = new TlvReader(encoding); @@ -371,11 +379,12 @@ public void TryReadByte_LengthTwo_ReturnsFalse() [Fact] public void TryReadInt16_LengthZero_ReturnsFalse() { - byte[] encoding = new byte[] { + byte[] encoding = new byte[] + { 0x81, 0x14, - 0x91, 0xFF, 0x00, - 0x11, 0x08, 0x31, 0x32, 0x82, 0x0B, 0x03, 0x02, 0x41, 0x42, - 0x04, 0x05, 0x61, 0x62, 0x63, 0x64, 0x65 + 0x91, 0xFF, 0x00, + 0x11, 0x08, 0x31, 0x32, 0x82, 0x0B, 0x03, 0x02, 0x41, 0x42, + 0x04, 0x05, 0x61, 0x62, 0x63, 0x64, 0x65 }; var reader = new TlvReader(encoding); @@ -391,11 +400,12 @@ public void TryReadInt16_LengthZero_ReturnsFalse() [Fact] public void TryReadInt16_LengthOne_ReturnsFalse() { - byte[] encoding = new byte[] { + byte[] encoding = new byte[] + { 0x81, 0x15, - 0x91, 0xFF, 0x01, 0x41, - 0x11, 0x08, 0x31, 0x32, 0x82, 0x0B, 0x03, 0x02, 0x41, 0x42, - 0x04, 0x05, 0x61, 0x62, 0x63, 0x64, 0x65, + 0x91, 0xFF, 0x01, 0x41, + 0x11, 0x08, 0x31, 0x32, 0x82, 0x0B, 0x03, 0x02, 0x41, 0x42, + 0x04, 0x05, 0x61, 0x62, 0x63, 0x64, 0x65, }; var reader = new TlvReader(encoding); @@ -411,11 +421,12 @@ public void TryReadInt16_LengthOne_ReturnsFalse() [Fact] public void TryReadUInt16_LengthZero_ReturnsFalse() { - byte[] encoding = new byte[] { + byte[] encoding = new byte[] + { 0x81, 0x14, - 0x91, 0xFF, 0x00, - 0x11, 0x08, 0x31, 0x32, 0x82, 0x0B, 0x03, 0x02, 0x41, 0x42, - 0x04, 0x05, 0x61, 0x62, 0x63, 0x64, 0x65 + 0x91, 0xFF, 0x00, + 0x11, 0x08, 0x31, 0x32, 0x82, 0x0B, 0x03, 0x02, 0x41, 0x42, + 0x04, 0x05, 0x61, 0x62, 0x63, 0x64, 0x65 }; var reader = new TlvReader(encoding); @@ -431,11 +442,12 @@ public void TryReadUInt16_LengthZero_ReturnsFalse() [Fact] public void TryReadUInt16_LengthOne_ReturnsFalse() { - byte[] encoding = new byte[] { + byte[] encoding = new byte[] + { 0x81, 0x15, - 0x91, 0xFF, 0x01, 0x41, - 0x11, 0x08, 0x31, 0x32, 0x82, 0x0B, 0x03, 0x02, 0x41, 0x42, - 0x04, 0x05, 0x61, 0x62, 0x63, 0x64, 0x65, + 0x91, 0xFF, 0x01, 0x41, + 0x11, 0x08, 0x31, 0x32, 0x82, 0x0B, 0x03, 0x02, 0x41, 0x42, + 0x04, 0x05, 0x61, 0x62, 0x63, 0x64, 0x65, }; var reader = new TlvReader(encoding); diff --git a/Yubico.DotNetPolyfills/src/AssemblyInfo.cs b/Yubico.DotNetPolyfills/src/AssemblyInfo.cs index b1da9f09..a8b816ed 100644 --- a/Yubico.DotNetPolyfills/src/AssemblyInfo.cs +++ b/Yubico.DotNetPolyfills/src/AssemblyInfo.cs @@ -14,4 +14,4 @@ using System; -[assembly:CLSCompliant(true)] +[assembly: CLSCompliant(true)] diff --git a/Yubico.NativeShims/CMakeLists.txt b/Yubico.NativeShims/CMakeLists.txt index 73accfe2..b1e6cdfd 100644 --- a/Yubico.NativeShims/CMakeLists.txt +++ b/Yubico.NativeShims/CMakeLists.txt @@ -1,32 +1,56 @@ -cmake_minimum_required(VERSION 3.10) +cmake_minimum_required(VERSION 3.13) +project(Yubico.NativeShims VERSION 1.10.1) +include(CheckCCompilerFlag) -project(Yubico.NativeShims VERSION 1.3.0) +if (APPLE OR UNIX) + if (APPLE) + set(PLATFORM_MACOS true) + set(BACKEND "macscard") + add_link_options("-exported_symbols_list ${CMAKE_CURRENT_SOURCE_DIR}/exports.llvm") + elseif(UNIX) + find_package(PkgConfig REQUIRED) + set(PLATFORM_LINUX true) + set(BACKEND "pcsc") + add_link_options("-Wl,-z,relro,-z,now,--version-script=${CMAKE_CURRENT_SOURCE_DIR}/exports.gnu") + endif() + if (CMAKE_C_COMPILER_ID STREQUAL "Clang" OR + CMAKE_C_COMPILER_ID STREQUAL "AppleClang" OR + CMAKE_C_COMPILER_ID STREQUAL "GNU") -if (APPLE) - set(PLATFORM_MACOS true) - set(BACKEND "macscard") -elseif(UNIX) - set(PLATFORM_LINUX true) - set(BACKEND "pcsc") - find_package(PkgConfig REQUIRED) + add_compile_options(-Wall -Wextra -Werror) + add_compile_options(-Wformat -Wformat-nonliteral -Wformat-security) + add_compile_options(-Wshadow) + add_compile_options(-Wcast-qual) + add_compile_options(-Wbad-function-cast) + add_compile_options(-pedantic -pedantic-errors) + add_compile_options(-fpic) + add_compile_options(-O2) + add_compile_definitions (-D_FORTIFY_SOURCE=2) + add_link_options(-fpic) + + check_c_compiler_flag("-fstack-protector-all" HAVE_STACK_PROTECTOR_ALL) + if (HAVE_STACK_PROTECTOR_ALL) + message(STATUS "-fstack-protector-all support detected") + add_compile_options(-fstack-protector-all) + add_link_options(-fstack-protector-all) + else () + check_c_compiler_flag("-fstack-protector" HAVE_STACK_PROTECTOR) + if(HAVE_STACK_PROTECTOR) + message(STATUS "-fstack-protector support detected") + add_compile_options(-fstack-protector) + add_link_options(-fstack-protector) + else () + message(WARNING "No stack protection supported.") + endif () + endif() + elseif() + message(WARNING "No compatible compiler found for setting additional security compiler flags.") + endif() elseif(WIN32) set(PLATFORM_WINDOWS true) set(BACKEND "winscard") -endif() - -# export list -if(APPLE AND (CMAKE_C_COMPILER_ID STREQUAL "Clang" OR - CMAKE_C_COMPILER_ID STREQUAL "AppleClang")) - # clang + lld - string(CONCAT CMAKE_SHARED_LINKER_FLAGS ${CMAKE_SHARED_LINKER_FLAGS} - " -exported_symbols_list ${CMAKE_CURRENT_SOURCE_DIR}/exports.llvm") -elseif(NOT MSVC) - # clang/gcc + gnu ld - string(CONCAT CMAKE_SHARED_LINKER_FLAGS ${CMAKE_SHARED_LINKER_FLAGS} - " -Wl,--version-script=${CMAKE_CURRENT_SOURCE_DIR}/exports.gnu") -else() - string(CONCAT CMAKE_SHARED_LINKER_FLAGS ${CMAKE_SHARED_LINKER_FLAGS} - " /def:\"${CMAKE_CURRENT_SOURCE_DIR}/exports.msvc\"") + add_link_options("/guard:cf" "/def:${CMAKE_CURRENT_SOURCE_DIR}/exports.msvc") + add_compile_options("/GS" "/Gs") endif() @@ -36,7 +60,6 @@ endif() include(${CMAKE_SOURCE_DIR}/cmake/pcscd.cmake) find_pcscd() - find_package(OpenSSL REQUIRED) # diff --git a/Yubico.NativeShims/Yubico.NativeShims.nuspec b/Yubico.NativeShims/Yubico.NativeShims.nuspec index 52265f24..48b1d8bf 100644 --- a/Yubico.NativeShims/Yubico.NativeShims.nuspec +++ b/Yubico.NativeShims/Yubico.NativeShims.nuspec @@ -2,7 +2,7 @@ Yubico.NativeShims - 1.6.1 + 1.0.0 Yubico AB Yubico AB @@ -21,17 +21,15 @@ + + - - - - - - + + diff --git a/Yubico.NativeShims/build-linux-amd64.sh b/Yubico.NativeShims/build-linux-amd64.sh new file mode 100644 index 00000000..de54e5eb --- /dev/null +++ b/Yubico.NativeShims/build-linux-amd64.sh @@ -0,0 +1,51 @@ +#!/bin/bash + +# Set environment variables +export VCPKG_INSTALLATION_ROOT=$GITHUB_WORKSPACE/vcpkg \ + PATH=/usr/local/bin:$PATH + +# Install necessary packages +sudo apt-get update -qq && \ +DEBIAN_FRONTEND=noninteractive sudo apt-get install -yq \ + git \ + tar \ + curl \ + zip \ + unzip \ + wget \ + build-essential \ + software-properties-common \ + ca-certificates \ + pkg-config \ + gnupg \ + libpcsclite-dev \ + zlib1g-dev \ + ninja-build \ + g++ \ + gcc + +# Install latest version of CMake for Ubuntu 20.04 +wget -O - https://apt.kitware.com/keys/kitware-archive-latest.asc 2>/dev/null | gpg --dearmor - | sudo tee /usr/share/keyrings/kitware-archive-keyring.gpg >/dev/null +echo 'deb [signed-by=/usr/share/keyrings/kitware-archive-keyring.gpg] https://apt.kitware.com/ubuntu/ focal main' | sudo tee /etc/apt/sources.list.d/kitware.list >/dev/null +sudo apt-get update -qq +sudo apt-get install cmake -yq + +# Install VCPKG +git clone https://github.com/Microsoft/vcpkg.git ${VCPKG_INSTALLATION_ROOT} && ${VCPKG_INSTALLATION_ROOT}/bootstrap-vcpkg.sh + +## Build +if [ ! -f ./CMakeLists.txt ]; then + cd ~/Yubico.NativeShims +fi + +build_dir="linux-x64" +rm -rf "$build_dir" +mkdir -p "$build_dir" + +echo "Building for x64-linux ..." +cmake -S . -B "$build_dir" \ + -DCMAKE_BUILD_TYPE=Release \ + -DCMAKE_TOOLCHAIN_FILE="$VCPKG_INSTALLATION_ROOT/scripts/buildsystems/vcpkg.cmake" \ + -DVCPKG_TARGET_TRIPLET=x64-linux + +cmake --build "$build_dir" -- -j $(nproc) diff --git a/Yubico.NativeShims/build-linux-arm64.sh b/Yubico.NativeShims/build-linux-arm64.sh new file mode 100644 index 00000000..e6bb8f3d --- /dev/null +++ b/Yubico.NativeShims/build-linux-arm64.sh @@ -0,0 +1,65 @@ +#!/bin/bash + +# Set environment variables +export VCPKG_INSTALLATION_ROOT=$GITHUB_WORKSPACE/vcpkg \ + VCPKG_FORCE_SYSTEM_BINARIES=1 \ + PATH=/usr/local/bin:$VCPKG_INSTALLATION_ROOT:$PATH + +# Install necessary packages +sudo apt-get update -qq && \ +DEBIAN_FRONTEND=noninteractive sudo apt-get install -yq \ + git \ + tar \ + curl \ + zip \ + unzip \ + wget \ + build-essential \ + software-properties-common \ + ca-certificates \ + pkg-config \ + gnupg \ + zlib1g-dev \ + ninja-build \ + g++-aarch64-linux-gnu \ + gcc-aarch64-linux-gnu + +# Install latest version of CMake for Ubuntu 20.04 +wget -O - https://apt.kitware.com/keys/kitware-archive-latest.asc 2>/dev/null | gpg --dearmor - | sudo tee /usr/share/keyrings/kitware-archive-keyring.gpg >/dev/null +echo 'deb [signed-by=/usr/share/keyrings/kitware-archive-keyring.gpg] https://apt.kitware.com/ubuntu/ focal main' | sudo tee /etc/apt/sources.list.d/kitware.list >/dev/null +sudo apt-get update -qq +sudo apt-get install cmake -yq + +# Install VCPKG +git clone https://github.com/Microsoft/vcpkg.git ${VCPKG_INSTALLATION_ROOT} && ${VCPKG_INSTALLATION_ROOT}/bootstrap-vcpkg.sh + +# Install arm64 version of libpcsclite +echo "deb [arch=arm64] http://ports.ubuntu.com/ubuntu-ports/ focal main restricted universe multiverse +deb [arch=arm64] http://ports.ubuntu.com/ubuntu-ports/ focal-updates main restricted universe multiverse +deb [arch=arm64] http://ports.ubuntu.com/ubuntu-ports/ focal-security main restricted universe multiverse +deb [arch=arm64] http://ports.ubuntu.com/ubuntu-ports/ focal-backports main restricted universe multiverse" | sudo tee -a /etc/apt/sources.list > /dev/null +sudo dpkg --add-architecture arm64 +sudo apt-get update -qq +sudo apt-get install libpcsclite-dev:arm64 -yq + +## Build +if [ ! -f ./CMakeLists.txt ]; then + cd ~/Yubico.NativeShims +fi + +# Add paths to our libraries so that CMake finds the correct arm64 ones +export PKG_CONFIG_PATH="/usr/lib/aarch64-linux-gnu/pkgconfig:$(pwd)/arm64-linux/vcpkg_installed/arm64-linux/lib/pkgconfig" + +build_dir=linux-arm64 +rm -rf "$build_dir" +mkdir -p "$build_dir" + +echo "Building for arm64-linux ..." +cmake -S . -B "$build_dir" \ + -DCMAKE_BUILD_TYPE=Release \ + -DCMAKE_TOOLCHAIN_FILE="$VCPKG_INSTALLATION_ROOT/scripts/buildsystems/vcpkg.cmake" \ + -DVCPKG_TARGET_TRIPLET="arm64-linux" \ + -DVCPKG_CHAINLOAD_TOOLCHAIN_FILE="$(pwd)/cmake/aarch64-linux-gnu.toolchain.cmake" \ + -DOPENSSL_ROOT_DIR=$(pwd)/linux-arm64/vcpkg_installed/arm64-linux + +cmake --build "$build_dir" -- -j $(nproc) diff --git a/Yubico.NativeShims/build-ubuntu.sh b/Yubico.NativeShims/build-ubuntu.sh deleted file mode 100644 index a8bf325b..00000000 --- a/Yubico.NativeShims/build-ubuntu.sh +++ /dev/null @@ -1,87 +0,0 @@ -# We use Docker Build Kit as it supports advanced features such as -# cross-architecture building using QEMU, and extracting files from -# the final build image. - -export DOCKER_BUILDKIT=1 - -# Download the Docker image / plugin that allows QEMU to run non- -# native container architectures. This step is necessary to run -# the cross build steps below. -docker run --pull always --rm --privileged multiarch/qemu-user-static --reset -p yes - - -# Parameter guide: -# -# Tag: Right now, we do not save these images to any container -# registry. Because of this, it is fine that we're using a static -# version number in the tag. If building native shims become something -# we need to do on a more regular basis (like daily), we can look into -# caching the build environment to save on our CI runner workload. -# -# File: Points to the docker file definition that we wish to build. -# Each flavor of Linux should have their own Dockerfile to customize -# the build process to that particular distribution. -# -# Platform: The Docker platform identifier to build. The platforms -# we're interested in as part of the SDK are: linux/{amd64,386,arm64,arm/v7} -# -# Build-args: We pass in the hosts' user and group ID so that all files -# are ACL'd according to the host system. -# -# Output: We tell Docker to output the contents of the final image to -# the local fileystem, inside of the artifacts/{distro} directory. -# Within that folder, there should be a folder for each platform built. -# This will typically mean that there is a `linux` directory, followed -# by another folder for the processor architecture. -# For example: `artifacts/linux/386` for the 32-bit Linux build -# -# . : This tells Docker to use the current directory as the basis for -# the "context" to pass into the image using the COPY Dockerfile -# instruction. This should be the Yubico.NativeShims folder containing -# this script, as well as the CMakeLists.txt file. -# -# Extending this script: -# -# If we're adding a new build, say for a new distribution, we should -# simply add another docker buildx command. We need to add a call for -# each of the supported processor architectures (usually amd64 and arm64). -# -# We may want to consider refactoring this script to use functions at -# some point to make adding new distributions and architectures even -# easier. - -# Distro: Ubuntu -# Arch: amd64/x64 -# Output: ./ubuntu-x64/libYubico.NativeShims.so -docker buildx build \ - --tag yubico/nativeshims-ubuntu:1.0 \ - --file docker/Ubuntu/Dockerfile \ - --platform=linux/amd64 \ - --build-arg USER_ID=`id -u` \ - --build-arg GROUP_ID=`id -g` \ - --output type=local,dest=ubuntu-x64 \ - . - -# Distro: Ubuntu -# Arch: i386/x86 -# Output: ./ubuntu-x86/libYubico.NativeShims.so -docker buildx build \ - --tag yubico/nativeshims-ubuntu:1.0 \ - --file docker/Ubuntu/Dockerfile \ - --platform=linux/386 \ - --build-arg USER_ID=`id -u` \ - --build-arg GROUP_ID=`id -g` \ - --output type=local,dest=ubuntu-x86 \ - . - -# Distro: Ubuntu -# Arch: arm64 -# Output: ./ubuntu-arm64/libYubico.NativeShims.so -docker buildx build \ - --tag yubico/nativeshims-ubuntu:1.0 \ - --file docker/Ubuntu/Dockerfile \ - --platform=linux/arm64 \ - --build-arg USER_ID=`id -u` \ - --build-arg GROUP_ID=`id -g` \ - --output type=local,dest=ubuntu-arm64 \ - . diff --git a/Yubico.NativeShims/build-windows.cmd b/Yubico.NativeShims/build-windows.cmd deleted file mode 100644 index 92aebfc8..00000000 --- a/Yubico.NativeShims/build-windows.cmd +++ /dev/null @@ -1,25 +0,0 @@ -:: Update to latest vcpkg baseline -pushd %VCPKG_INSTALLATION_ROOT% -git checkout master -git restore . -git pull -vcpkg x-update-baseline -popd - -:: 32-bit builds -cmake -S . -B build32 -A Win32 -DCMAKE_TOOLCHAIN_FILE=%VCPKG_INSTALLATION_ROOT%/scripts/buildsystems/vcpkg.cmake -DVCPKG_TARGET_TRIPLET=x86-windows-static -cmake --build build32 --config Release -mkdir win-x86 -copy build32\Release\Yubico.NativeShims.dll win-x86 - -:: 64-bit builds -cmake -S . -B build64 -A x64 -DCMAKE_TOOLCHAIN_FILE=%VCPKG_INSTALLATION_ROOT%/scripts/buildsystems/vcpkg.cmake -DVCPKG_TARGET_TRIPLET=x64-windows-static -cmake --build build64 --config Release -mkdir win-x64 -copy build64\Release\Yubico.NativeShims.dll win-x64 - -:: ARM64 builds -cmake -S . -B buildarm -A arm64 -DCMAKE_TOOLCHAIN_FILE=%VCPKG_INSTALLATION_ROOT%/scripts/buildsystems/vcpkg.cmake -DVCPKG_TARGET_TRIPLET=arm64-windows-static -cmake --build buildarm --config Release -mkdir win-arm64 -copy buildarm\Release\Yubico.NativeShims.dll win-arm64 \ No newline at end of file diff --git a/Yubico.NativeShims/build-windows.ps1 b/Yubico.NativeShims/build-windows.ps1 new file mode 100644 index 00000000..94817659 --- /dev/null +++ b/Yubico.NativeShims/build-windows.ps1 @@ -0,0 +1,25 @@ +# Update to latest vcpkg baseline +Push-Location $env:VCPKG_INSTALLATION_ROOT +git checkout master +git restore . +git pull +vcpkg x-update-baseline +Pop-Location + +# 32-bit builds +cmake -S . -B build32 -A Win32 -DCMAKE_TOOLCHAIN_FILE="$env:VCPKG_INSTALLATION_ROOT\scripts\buildsystems\vcpkg.cmake" -DVCPKG_TARGET_TRIPLET=x86-windows-static +cmake --build build32 --config Release +mkdir win-x86 +Copy-Item build32\Release\Yubico.NativeShims.dll win-x86 + +# 64-bit builds +cmake -S . -B build64 -A x64 -DCMAKE_TOOLCHAIN_FILE="$env:VCPKG_INSTALLATION_ROOT\scripts\buildsystems\vcpkg.cmake" -DVCPKG_TARGET_TRIPLET=x64-windows-static +cmake --build build64 --config Release +mkdir win-x64 +Copy-Item build64\Release\Yubico.NativeShims.dll win-x64 + +# ARM64 builds +cmake -S . -B buildarm -A arm64 -DCMAKE_TOOLCHAIN_FILE="$env:VCPKG_INSTALLATION_ROOT\scripts\buildsystems\vcpkg.cmake" -DVCPKG_TARGET_TRIPLET=arm64-windows-static +cmake --build buildarm --config Release +mkdir win-arm64 +Copy-Item buildarm\Release\Yubico.NativeShims.dll win-arm64 \ No newline at end of file diff --git a/Yubico.NativeShims/cmake/aarch64-linux-gnu.toolchain.cmake b/Yubico.NativeShims/cmake/aarch64-linux-gnu.toolchain.cmake new file mode 100644 index 00000000..3895a361 --- /dev/null +++ b/Yubico.NativeShims/cmake/aarch64-linux-gnu.toolchain.cmake @@ -0,0 +1,7 @@ +set(CMAKE_SYSTEM_NAME Linux) +set(CMAKE_SYSTEM_PROCESSOR aarch64) + +set(CMAKE_C_COMPILER aarch64-linux-gnu-gcc) +set(CMAKE_CXX_COMPILER aarch64-linux-gnu-g++) + +set(CMAKE_INTERPROCEDURAL_OPTIMIZATION TRUE) \ No newline at end of file diff --git a/Yubico.NativeShims/docker/Ubuntu/Dockerfile b/Yubico.NativeShims/docker/Ubuntu/Dockerfile deleted file mode 100644 index c8290a62..00000000 --- a/Yubico.NativeShims/docker/Ubuntu/Dockerfile +++ /dev/null @@ -1,86 +0,0 @@ -# We use Bionic as the basis for our image. Bionic is the last Ubuntu long-term support -# release that is both still supported and still supports i386 processors. Once Bionic -# leaves support, we can consider upgrading to the next LTS release. -FROM ubuntu:bionic AS env - -# These arguments are passed in from the console or by Docker-CLI itself. User/Group ID -# is used to run the shell as the host's user identity. Artifact_dir should be set to -# the NuGet runtime-id for this platform (e.g. ubuntu-x64) to aid in artifact discovery -# in the GitHub Action workflow. -ARG USER_ID -ARG GROUP_ID -ARG ARTIFACT_DIR - -# Set up basic environment variables such as the path. -ENV PATH=/usr/local/bin:$PATH - -# Add the host user and group to the image. -RUN groupadd -f -g ${GROUP_ID} local && useradd -u ${USER_ID} -g ${GROUP_ID} -s /bin/sh local - -# Install build tools -RUN apt-get update -qq \ -&& DEBIAN_FRONTEND=noninteractive apt-get install -yq \ - wget \ - ca-certificates \ - gnupg \ - software-properties-common \ - build-essential \ - pkg-config \ - ninja-build \ -&& apt-get clean \ -&& rm -rf /var/lib/apt/lists/* /tmp/* /var/temp/* - -# Install latest CMake -# Ubuntu Bionic contains a very old version of CMake (3.10). Our project requires a newer -# version of the tool. This is the easiest way to update CMake using the official builds -# from Kitware (makers of CMake). -RUN apt-get update -qq \ -&& wget -O - https://apt.kitware.com/keys/kitware-archive-latest.asc 2>/dev/null | apt-key add - \ -&& add-apt-repository 'deb https://apt.kitware.com/ubuntu/ bionic main' \ -&& apt-get update -qq \ -&& apt-get install cmake -yq \ -&& cmake -version - -# Install build dependencies -# This is where we should add any additional dependencies needed by Yubico.NativeShims. -# We could use vcpkg to help with dependencies, but for Linux, the distro's package -# manager is still almost always going to be the easiest way of finding the necessary -# headers and pre-built libraries. Be sure to use the -dev packages, as these typically -# denote the package that contains headers and libs. -RUN apt-get update -qq \ -&& apt-get install -yq \ - libpcsclite-dev \ - libssl-dev - -# Snapshot the base environment. If we ever decide to cache our images in a container -# registry, `env` is the target we'd want to capture. The dependencies will be installed -# but we have not yet copied the source code to build into the image. That happens in -# this (devel) stage. -FROM env AS devel -# Let's work out of a folder that's out of the way on the filesystem. -WORKDIR /home/build -# Copy the host context (source code) into the image. See the notes in the shell script -# that invokes Docker to see the other end of specifying the context. Copies all of the -# host context (recursively) into the current working dir in the Docker image. -COPY . . -RUN rm -rf artifacts - -# Build the Yubico.NativeShims shared object -# Now we take the `devel` target, and fork another image for building. This way, we can -# quickly roll back a failed build and retry (or try interactively). Put all of the -# build instructions in this stage. For now, this simply means generating the CMake -# cache, and building using CMake. We move the build artifacts into a well known -# location to help the artifact stage. -FROM devel AS build -RUN cmake -S . -B build_out -DCMAKE_BUILD_TYPE=Release -RUN cmake --build build_out --target all -v -RUN mkdir -p /home/build/artifacts/$ARTIFACT_DIR \ -&& cp /home/build/build_out/*.so /home/build/artifacts/$ARTIFACT_DIR - -# Copy over the build artifacts to a blank image. This way we can easily retrieve the -# build results without copying all of the previous image's filesystem. `Scratch` is -# a completely blank image. We then use the `COPY` instruction to pull only the files -# we care about into this blank space. The `--output` argument to the `docker` command -# specifies what we do with this result. -FROM scratch AS build_install -COPY --from=build /home/build/artifacts/$ARTIFACT_DIR/ . diff --git a/Yubico.NativeShims/msbuild/Yubico.NativeShims.targets b/Yubico.NativeShims/msbuild/Yubico.NativeShims.targets index 0be8b18a..89de7cac 100644 --- a/Yubico.NativeShims/msbuild/Yubico.NativeShims.targets +++ b/Yubico.NativeShims/msbuild/Yubico.NativeShims.targets @@ -1,8 +1,12 @@  - + Since .NET Framework is Windows only, we only need to worry about that platform. + --> + + Yubico.NativeShims.dll @@ -10,6 +14,8 @@ false + + Yubico.NativeShims.dll @@ -17,6 +23,8 @@ false + + Yubico.NativeShims.dll diff --git a/Yubico.NativeShims/pcsc.c b/Yubico.NativeShims/pcsc.c index 1bf6c148..5f580dd0 100644 --- a/Yubico.NativeShims/pcsc.c +++ b/Yubico.NativeShims/pcsc.c @@ -26,7 +26,7 @@ typedef struct #pragma pack() -int32_t +uint32_t NATIVEAPI Native_SCardEstablishContext( uint32_t dwScope, @@ -41,7 +41,7 @@ Native_SCardEstablishContext( ); } -int32_t +uint32_t NATIVEAPI Native_SCardReleaseContext( SCARDCONTEXT hContext @@ -50,7 +50,7 @@ Native_SCardReleaseContext( return SCardReleaseContext(hContext); } -int32_t +uint32_t NATIVEAPI Native_SCardConnect( SCARDCONTEXT hContext, @@ -74,7 +74,7 @@ Native_SCardConnect( return status; } -int32_t +uint32_t NATIVEAPI Native_SCardReconnect( SCARDHANDLE hCard, @@ -96,7 +96,7 @@ Native_SCardReconnect( return status; } -int32_t +uint32_t NATIVEAPI Native_SCardDisconnect( SCARDHANDLE hCard, @@ -109,7 +109,7 @@ Native_SCardDisconnect( ); } -int32_t +uint32_t NATIVEAPI Native_SCardBeginTransaction( SCARDHANDLE hCard @@ -118,7 +118,7 @@ Native_SCardBeginTransaction( return SCardBeginTransaction(hCard); } -int32_t +uint32_t NATIVEAPI Native_SCardEndTransaction( SCARDHANDLE hCard, @@ -131,7 +131,7 @@ Native_SCardEndTransaction( ); } -int32_t +uint32_t NATIVEAPI Native_SCardGetStatusChange( SCARDCONTEXT hContext, @@ -158,7 +158,7 @@ Native_SCardGetStatusChange( memcpy(readerStates[i].rgbAtr, rgReaderStates[i].rgbAtr, sizeof(readerStates[i].rgbAtr)); } - int32_t result = SCardGetStatusChange( + uint32_t result = SCardGetStatusChange( hContext, dwTimeout, readerStates, @@ -178,7 +178,7 @@ Native_SCardGetStatusChange( return result; } -int32_t +uint32_t NATIVEAPI Native_SCardTransmit( SCARDHANDLE hCard, @@ -204,7 +204,7 @@ Native_SCardTransmit( return status; } -int32_t +uint32_t NATIVEAPI Native_SCardListReaders( SCARDCONTEXT hContext, @@ -224,7 +224,7 @@ Native_SCardListReaders( return status; } -int32_t +uint32_t NATIVEAPI Native_SCardCancel( SCARDCONTEXT hContext diff --git a/Yubico.NativeShims/ssl.cmac.c b/Yubico.NativeShims/ssl.cmac.c index fbbcc464..23647124 100644 --- a/Yubico.NativeShims/ssl.cmac.c +++ b/Yubico.NativeShims/ssl.cmac.c @@ -1,9 +1,6 @@ #include "native_abi.h" #include "Yubico.NativeShims.h" #include "openssl/evp.h" -#ifdef PLATFORM_LINUX -#include "openssl/cmac.h" -#endif #define CMAC_MAX_BLOCK_SIZE 16 typedef void* Native_EVP_MAC_CTX; @@ -12,7 +9,6 @@ Native_EVP_MAC_CTX NATIVEAPI Native_CMAC_EVP_MAC_CTX_new() { -#ifndef PLATFORM_LINUX EVP_MAC *mac = NULL; EVP_MAC_CTX *macCtx = NULL; @@ -24,9 +20,7 @@ Native_CMAC_EVP_MAC_CTX_new() } return macCtx; -#else - return CMAC_CTX_new(); -#endif + } void @@ -35,11 +29,7 @@ Native_EVP_MAC_CTX_free( Native_EVP_MAC_CTX c ) { -#ifndef PLATFORM_LINUX EVP_MAC_CTX_free(c); -#else - CMAC_CTX_free(c); -#endif } int32_t @@ -51,7 +41,6 @@ Native_CMAC_EVP_MAC_init( int32_t keyLen ) { -#ifndef PLATFORM_LINUX char *cipherString; int32_t cipherStringLen; int32_t blockSize; @@ -88,26 +77,7 @@ Native_CMAC_EVP_MAC_init( }; return EVP_MAC_init(c, keyData, keyLen, params); -#else - EVP_CIPHER *evpCipher; - - switch (algorithm) - { - default: - evpCipher = EVP_aes_128_cbc(); - break; - - case 2: - evpCipher = EVP_aes_192_cbc(); - break; - case 3: - evpCipher = EVP_aes_256_cbc(); - break; - } - - return CMAC_Init(c, keyData, keyLen, evpCipher, NULL); -#endif } int32_t @@ -118,11 +88,7 @@ Native_CMAC_EVP_MAC_update( int32_t inLen ) { -#ifndef PLATFORM_LINUX return EVP_MAC_update(c, input, inLen); -#else - return CMAC_Update(c, input, inLen); -#endif } int32_t @@ -136,11 +102,8 @@ Native_CMAC_EVP_MAC_final( { int status; size_t outputLen = (size_t)outputSize; -#ifndef PLATFORM_LINUX status = EVP_MAC_final(c, output, &outputLen, outputSize); -#else - status = CMAC_Final(c, output, &outputLen); -#endif + *outLen = (int32_t)outputLen; return status; } diff --git a/Yubico.YubiKey/docs/users-manual/getting-started/overview-of-sdk.md b/Yubico.YubiKey/docs/users-manual/getting-started/overview-of-sdk.md index 8305a50a..dfbc8e7c 100644 --- a/Yubico.YubiKey/docs/users-manual/getting-started/overview-of-sdk.md +++ b/Yubico.YubiKey/docs/users-manual/getting-started/overview-of-sdk.md @@ -44,7 +44,7 @@ in the standard but not actually implemented in Framework 4.6.x. | ---- | ---- | ---- | | macOS | x64, arm64 | Catalina, Big Sur | | Windows | x86, x64, arm64 | Windows 10, Windows 11 | -| Linux | x86, x64, arm64 | Debian, Ubuntu, RHEL, CentOS | +| Linux | x64, arm64 | Debian, Ubuntu, RHEL, CentOS | ## Supported YubiKey applications diff --git a/Yubico.YubiKey/docs/users-manual/getting-started/whats-new.md b/Yubico.YubiKey/docs/users-manual/getting-started/whats-new.md index a9fc80f1..44f20b48 100644 --- a/Yubico.YubiKey/docs/users-manual/getting-started/whats-new.md +++ b/Yubico.YubiKey/docs/users-manual/getting-started/whats-new.md @@ -15,7 +15,43 @@ limitations under the License. --> # What's new in the SDK? Here you can find all of the updates and release notes for published versions of the SDK. - +## 1.10.x Releases + +### 1.10.0 + +Release date: April 10th, 2024 + +This is a release aimed to address inconsistencies in dependencies (OpenSSL), compiler warnings and hardening. The objective of compiler options hardening is to produce application binaries (executables) with security mechanisms against potential attacks and/or misbehavior. is to produce application binaries (executables) with security mechanisms against potential attacks and/or misbehavior. + +This release improves our native dependencies exposed through the `Yubico.NativeShims` package. We have also worked to improve the build and test experience of this repository by improving our automation and build files. + +Changes: +- **Yubico.NativeShims targets OpenSSL version 3.x on all platforms** - OpenSSL v1.1.x has reached end-of-life. The SDK now removes this dependency on all platforms, now upgrading to the supported 3.x version. +- **Dropped support for 32-bit Linux** - Yubico.NativeShims no longer builds for 32-bit (x86) Linux. We now depend on Ubuntu releases that contain OpenSSL 3.x by default. These newer releases no longer have mainstream support for this platform. +- **[Compilation hardening of Yubico.NativeShims](https://github.com/Yubico/Yubico.NET.SDK/pull/67)** - Added commonly used compiler flags to increase security and code quality + **MacOS / Linux:** + -Wformat: Warn about format string issues in printf-like functions. + -Wformat-nonliteral: Warn about format strings that are not string literals. + -Wformat-security: Warn about potential security issues related to format strings. + -Wall: Enable most warning messages + -Wextra: Enable some additional warning messages not included in -Wall + -Werror: Treat all warnings as errors + -Wcast-qual: Warn when casting away const-ness + -Wshadow: Warn when a local variable shadows another variable + -pedantic: Issue warnings for language features beyond the C standard + -pedantic-errors: Treat pedantic warnings as errors + -Wbad-function-cast: Warn about dubious function pointer casts + -O2: Optimize code for performance + -fpic: Generate position-independent code + -fstack-protector-all: Enable stack protection for all functions + -D_FORTIFY_SOURCE=2: Enable runtime and compile-time checks for certain security-critical functions + **Windows flags:** + /guard:cf: Enable control flow guard security feature + /GS: Enable buffer security check + /Gs: Control stack security check +- [Addressed compiler warning concerning Runtime Identifiers (RID) ](https://github.com/Yubico/Yubico.NET.SDK/issues/59) +- **Enabled `dotnet format`** - The repository now uses `dotnet format` to ensure that pull requests adhere to the repository's coding standards. A pass of the tool has been run against the entire repository and a new baseline has been checked in. + ## 1.9.x Releases ### 1.9.1 diff --git a/Yubico.YubiKey/examples/Fido2SampleCode/KeyCollector/Fido2SampleKeyCollector.cs b/Yubico.YubiKey/examples/Fido2SampleCode/KeyCollector/Fido2SampleKeyCollector.cs index ecc73524..890c491d 100644 --- a/Yubico.YubiKey/examples/Fido2SampleCode/KeyCollector/Fido2SampleKeyCollector.cs +++ b/Yubico.YubiKey/examples/Fido2SampleCode/KeyCollector/Fido2SampleKeyCollector.cs @@ -24,16 +24,16 @@ namespace Yubico.YubiKey.Sample.Fido2SampleCode // This sample key collector is specifically built for FIDO2 only. public class Fido2SampleKeyCollector { - // This allows the caller to specify what the operation is. - // Some messages (such as Touch) can contain more information if this is - // known. - public Fido2KeyCollectorOperation Operation { get; set; } - public Fido2SampleKeyCollector() { Operation = Fido2KeyCollectorOperation.None; } + // This allows the caller to specify what the operation is. + // Some messages (such as Touch) can contain more information if this is + // known. + public Fido2KeyCollectorOperation Operation { get; set; } + public virtual bool Fido2SampleKeyCollectorDelegate(KeyEntryData keyEntryData) { if (keyEntryData is null) @@ -41,17 +41,20 @@ public virtual bool Fido2SampleKeyCollectorDelegate(KeyEntryData keyEntryData) return false; } - if (keyEntryData.IsRetry == true) + if (keyEntryData.IsRetry) { SampleMenu.WriteMessage(MessageType.Title, 0, "A previous entry was incorrect, do you want to retry?"); if (!(keyEntryData.RetriesRemaining is null)) { - string retryString = ((int)keyEntryData.RetriesRemaining).ToString("D", CultureInfo.InvariantCulture); - SampleMenu.WriteMessage(MessageType.Title, 0, "(retries remainin until blocked: " + retryString + ")"); + string retryString = + ((int)keyEntryData.RetriesRemaining).ToString("D", CultureInfo.InvariantCulture); + SampleMenu.WriteMessage(MessageType.Title, 0, + "(retries remainin until blocked: " + retryString + ")"); } + SampleMenu.WriteMessage(MessageType.Title, 0, "y/n"); char[] answer = SampleMenu.ReadResponse(out int _); - if ((answer.Length == 0) || ((answer[0] != 'y') && (answer[0] != 'Y'))) + if (answer.Length == 0 || (answer[0] != 'y' && answer[0] != 'Y')) { return false; } @@ -70,18 +73,22 @@ public virtual bool Fido2SampleKeyCollectorDelegate(KeyEntryData keyEntryData) case KeyEntryRequest.TouchRequest: ReportOperation(); - SampleMenu.WriteMessage(MessageType.Title, 0, "touch the YubiKey's contact to complete the operation.\n"); + SampleMenu.WriteMessage(MessageType.Title, 0, + "touch the YubiKey's contact to complete the operation.\n"); return true; case KeyEntryRequest.EnrollFingerprint: if (!(keyEntryData.LastBioEnrollSampleResult is null)) { string lastResult = keyEntryData.LastBioEnrollSampleResult.LastEnrollSampleStatus.ToString(); - SampleMenu.WriteMessage(MessageType.Title, 0, " Sample result: " + lastResult); + SampleMenu.WriteMessage(MessageType.Title, 0, + " Sample result: " + lastResult); SampleMenu.WriteMessage( MessageType.Title, 0, - "Number of good samples still needed: " + keyEntryData.LastBioEnrollSampleResult.RemainingSampleCount); + "Number of good samples still needed: " + + keyEntryData.LastBioEnrollSampleResult.RemainingSampleCount); } + SampleMenu.WriteMessage(MessageType.Title, 0, "\nPlease provide a fingerprint sample.\n"); return true; @@ -91,7 +98,8 @@ public virtual bool Fido2SampleKeyCollectorDelegate(KeyEntryData keyEntryData) return true; case KeyEntryRequest.SetFido2Pin: - SampleMenu.WriteMessage(MessageType.Title, 0, "Setting the FIDO2 application's PIN, enter the PIN."); + SampleMenu.WriteMessage(MessageType.Title, 0, + "Setting the FIDO2 application's PIN, enter the PIN."); collectedValue = SampleMenu.ReadResponse(out int _); pinValue = ConvertCharArrayToByteArray(collectedValue); keyEntryData.SubmitValue(pinValue); @@ -142,7 +150,8 @@ private void ReportOperation() break; case Fido2KeyCollectorOperation.Reset: - SampleMenu.WriteMessage(MessageType.Title, 0, "\nThe YubiKey is trying to reset the FIDO2 application,"); + SampleMenu.WriteMessage(MessageType.Title, 0, + "\nThe YubiKey is trying to reset the FIDO2 application,"); break; } } diff --git a/Yubico.YubiKey/examples/Fido2SampleCode/Run/Fido2SampleGui.cs b/Yubico.YubiKey/examples/Fido2SampleCode/Run/Fido2SampleGui.cs index c0ac93c7..f7d830a2 100644 --- a/Yubico.YubiKey/examples/Fido2SampleCode/Run/Fido2SampleGui.cs +++ b/Yubico.YubiKey/examples/Fido2SampleCode/Run/Fido2SampleGui.cs @@ -13,11 +13,11 @@ // limitations under the License. #if WINDOWS using System; -using System.Windows.Forms; using System.Drawing; +using System.Security.Cryptography; using System.Threading; using System.Threading.Tasks; -using System.Security.Cryptography; +using System.Windows.Forms; using Yubico.YubiKey; using Yubico.YubiKey.Sample.SharedCode; @@ -44,7 +44,7 @@ public Fido2SampleGui() public void RunSample() { using var tokenSource = new CancellationTokenSource(); - var sampleRunTask = Task.Run( () => CreateSampleRunThread(), tokenSource.Token); + var sampleRunTask = Task.Run(() => CreateSampleRunThread(), tokenSource.Token); _ = _parentForm.ShowDialog(); tokenSource.Cancel(); } @@ -125,7 +125,7 @@ public ParentForm() { Answered = true; Text = "FIDO2 Sample"; - Size = new Size(600,660); + Size = new Size(600, 660); MaximizeBox = false; MinimizeBox = false; StartPosition = FormStartPosition.CenterScreen; @@ -331,7 +331,7 @@ public class PinPopupForm : Form public PinPopupForm(string message) { Text = "User Action Required"; - Size = new Size(400,400); + Size = new Size(400, 400); MaximizeBox = false; MinimizeBox = false; ControlBox = true; @@ -399,7 +399,7 @@ public PinPopupForm(string message) protected override void OnShown(EventArgs e) { - _ = (_state < 3) ? _pinBox.Focus() : _newPinBox.Focus(); + _ = _state < 3 ? _pinBox.Focus() : _newPinBox.Focus(); } private void OkButton_Click(object sender, EventArgs e) @@ -468,7 +468,7 @@ private int UpdatePinBox(KeyEventArgs e, Span pinBuffer, int currentLen) return 0; } - if ((e.KeyValue < 0x21) || (e.KeyValue > 0x7E) || (currentLen >= 63)) + if (e.KeyValue < 0x21 || e.KeyValue > 0x7E || currentLen >= 63) { EndPinPopup(DialogResult.Retry); return 0; @@ -571,7 +571,7 @@ public class FpTouchPopupForm : Form public FpTouchPopupForm(string message) { Text = "User Action Required"; - Size = new Size(400,400); + Size = new Size(400, 400); MaximizeBox = false; MinimizeBox = false; ControlBox = true; @@ -644,4 +644,4 @@ protected override void Dispose(bool disposing) } #pragma warning restore CA1303 } -#endif \ No newline at end of file +#endif diff --git a/Yubico.YubiKey/examples/Fido2SampleCode/Run/Fido2SampleRun.Operations.cs b/Yubico.YubiKey/examples/Fido2SampleCode/Run/Fido2SampleRun.Operations.cs index a6cfae1f..d28fbbad 100644 --- a/Yubico.YubiKey/examples/Fido2SampleCode/Run/Fido2SampleRun.Operations.cs +++ b/Yubico.YubiKey/examples/Fido2SampleCode/Run/Fido2SampleRun.Operations.cs @@ -13,16 +13,16 @@ // limitations under the License. using System; -using System.Text; using System.Collections.Generic; +using System.Globalization; +using System.Linq; using System.Security.Cryptography; -using Yubico.YubiKey.Sample.SharedCode; +using System.Text; using Yubico.YubiKey.Cryptography; using Yubico.YubiKey.Fido2; using Yubico.YubiKey.Fido2.Commands; using Yubico.YubiKey.Fido2.Cose; -using System.Globalization; -using System.Linq; +using Yubico.YubiKey.Sample.SharedCode; namespace Yubico.YubiKey.Sample.Fido2SampleCode { @@ -34,8 +34,8 @@ public partial class Fido2SampleRun { public bool RunMenuItem(Fido2MainMenuItem menuItem) { - if ((menuItem >= Fido2MainMenuItem.MakeCredential) - &&(menuItem < Fido2MainMenuItem.Reset)) + if (menuItem >= Fido2MainMenuItem.MakeCredential + && menuItem < Fido2MainMenuItem.Reset) { SampleMenu.WriteMessage( MessageType.Title, 0, @@ -720,7 +720,7 @@ public bool RunDeleteLargeBlobData() CredentialUserInfo userInfo = SelectCredential(credentialData, credentialCount); - if ((userInfo is null) || (userInfo.LargeBlobKey is null)) + if (userInfo is null || userInfo.LargeBlobKey is null) { SampleMenu.WriteMessage( MessageType.Title, 0, @@ -1194,7 +1194,7 @@ private int FindCredential(ReadOnlyMemory credentialId) } } - return (index < _credentialList.Count) ? index : -1; + return index < _credentialList.Count ? index : -1; } // This does not build a real ClientDataHash. It builds something that @@ -1490,7 +1490,7 @@ private static void ReportCredential( } if (largeBlobReport) { - string lbKeyStatus = (userInfo.LargeBlobKey is null) ? "not available" : "available"; + string lbKeyStatus = userInfo.LargeBlobKey is null ? "not available" : "available"; SampleMenu.WriteMessage(MessageType.Title, 0, " Large Blob Key: " + lbKeyStatus); SampleMenu.WriteMessage(MessageType.Title, 0, "-----------"); } diff --git a/Yubico.YubiKey/examples/Fido2SampleCode/Run/Fido2SampleRun.cs b/Yubico.YubiKey/examples/Fido2SampleCode/Run/Fido2SampleRun.cs index 7a079f59..86467759 100644 --- a/Yubico.YubiKey/examples/Fido2SampleCode/Run/Fido2SampleRun.cs +++ b/Yubico.YubiKey/examples/Fido2SampleCode/Run/Fido2SampleRun.cs @@ -13,8 +13,8 @@ // limitations under the License. using System.Collections.Generic; -using Yubico.YubiKey.Sample.SharedCode; using Yubico.YubiKey.Fido2; +using Yubico.YubiKey.Sample.SharedCode; namespace Yubico.YubiKey.Sample.Fido2SampleCode { diff --git a/Yubico.YubiKey/examples/Fido2SampleCode/YubiKeyOperations/Fido2Protocol.cs b/Yubico.YubiKey/examples/Fido2SampleCode/YubiKeyOperations/Fido2Protocol.cs index 6654fda6..653b3839 100644 --- a/Yubico.YubiKey/examples/Fido2SampleCode/YubiKeyOperations/Fido2Protocol.cs +++ b/Yubico.YubiKey/examples/Fido2SampleCode/YubiKeyOperations/Fido2Protocol.cs @@ -13,10 +13,10 @@ // limitations under the License. using System; -using System.Text; -using System.Linq; using System.Collections.Generic; +using System.Linq; using System.Security.Cryptography; +using System.Text; using Yubico.YubiKey.Fido2; using Yubico.YubiKey.Fido2.Commands; diff --git a/Yubico.YubiKey/examples/OathSampleCode/KeyCollector/SampleKeyCollector.cs b/Yubico.YubiKey/examples/OathSampleCode/KeyCollector/SampleKeyCollector.cs index f0a77493..6c5efe06 100644 --- a/Yubico.YubiKey/examples/OathSampleCode/KeyCollector/SampleKeyCollector.cs +++ b/Yubico.YubiKey/examples/OathSampleCode/KeyCollector/SampleKeyCollector.cs @@ -21,7 +21,7 @@ namespace Yubico.YubiKey.Sample.OathSampleCode // This KeyCollector is not secure. It simply asks for the user to enter password at the keyboard, // with no hiding. public static class SampleKeyCollector - { + { // This is the callback. When the SDK needs a password, // this is the method that will be called. public static bool SampleKeyCollectorDelegate(KeyEntryData keyEntryData) diff --git a/Yubico.YubiKey/examples/OathSampleCode/Run/OathSampleRun.Operations.cs b/Yubico.YubiKey/examples/OathSampleCode/Run/OathSampleRun.Operations.cs index af341283..6caea741 100644 --- a/Yubico.YubiKey/examples/OathSampleCode/Run/OathSampleRun.Operations.cs +++ b/Yubico.YubiKey/examples/OathSampleCode/Run/OathSampleRun.Operations.cs @@ -12,8 +12,8 @@ // See the License for the specific language governing permissions and // limitations under the License. -using Yubico.YubiKey.Sample.SharedCode; using Yubico.YubiKey.Oath; +using Yubico.YubiKey.Sample.SharedCode; namespace Yubico.YubiKey.Sample.OathSampleCode { @@ -224,7 +224,7 @@ private bool RunRenameCredentialMenuItem(int? index) _yubiKeyChosen, SampleKeyCollector.SampleKeyCollectorDelegate, _credentialChosen, - "Yubico", + "Yubico", "testRename@example.com"); } else diff --git a/Yubico.YubiKey/examples/OathSampleCode/YubiKeyOperations/AddCredential.cs b/Yubico.YubiKey/examples/OathSampleCode/YubiKeyOperations/AddCredential.cs index ee18e061..a449e443 100644 --- a/Yubico.YubiKey/examples/OathSampleCode/YubiKeyOperations/AddCredential.cs +++ b/Yubico.YubiKey/examples/OathSampleCode/YubiKeyOperations/AddCredential.cs @@ -15,8 +15,8 @@ using System; using System.Globalization; using System.Text; -using Yubico.YubiKey.Sample.SharedCode; using Yubico.YubiKey.Oath; +using Yubico.YubiKey.Sample.SharedCode; namespace Yubico.YubiKey.Sample.OathSampleCode { @@ -266,7 +266,8 @@ private static Credential CollectTotpCredential(SampleMenu menuObject) SampleMenu.WriteMessage(MessageType.Title, 0, "Set require touch property? Answer Yes or No."); _ = SampleMenu.ReadResponse(out string touch); - var credential = new Credential { + var credential = new Credential + { Issuer = issuer, AccountName = account, Type = CredentialType.Totp, diff --git a/Yubico.YubiKey/examples/OathSampleCode/YubiKeyOperations/CalculateCredentials.cs b/Yubico.YubiKey/examples/OathSampleCode/YubiKeyOperations/CalculateCredentials.cs index 36382a47..4a15bda0 100644 --- a/Yubico.YubiKey/examples/OathSampleCode/YubiKeyOperations/CalculateCredentials.cs +++ b/Yubico.YubiKey/examples/OathSampleCode/YubiKeyOperations/CalculateCredentials.cs @@ -56,7 +56,7 @@ public static bool RunCalculateOneCredential( return true; } - private static void ReportAllResults(IDictionary credentials) + private static void ReportAllResults(IDictionary credentials) { // Are there any? var outputList = new StringBuilder(""); diff --git a/Yubico.YubiKey/examples/OathSampleCode/YubiKeyOperations/ChooseCredential.cs b/Yubico.YubiKey/examples/OathSampleCode/YubiKeyOperations/ChooseCredential.cs index 7f5c94bb..ed01b25a 100644 --- a/Yubico.YubiKey/examples/OathSampleCode/YubiKeyOperations/ChooseCredential.cs +++ b/Yubico.YubiKey/examples/OathSampleCode/YubiKeyOperations/ChooseCredential.cs @@ -53,7 +53,7 @@ public static bool RunChooseCredential( return false; } - if ((credentials.Count == 1) && (alwaysAsk == false)) + if (credentials.Count == 1 && alwaysAsk == false) { chosenCredential = credentials[0]; return true; @@ -68,7 +68,7 @@ public static bool RunChooseCredential( } int indexChosen = menuObject.RunMenu("Which Credential do you want to use?", choices); - if ((indexChosen >= 0) && (indexChosen < credentials.Count)) + if (indexChosen >= 0 && indexChosen < credentials.Count) { chosenCredential = credentials[indexChosen]; return true; @@ -98,7 +98,7 @@ public static bool RunChooseAddCredentialOption(SampleMenu menuObject, out int? int indexChosen = menuObject.RunMenu("How would you want to add it?", choices); - if ((indexChosen >= 0) && (indexChosen < choices.Length)) + if (indexChosen >= 0 && indexChosen < choices.Length) { index = indexChosen; return true; @@ -130,7 +130,7 @@ public static bool RunChooseCredentialOption(SampleMenu menuObject, out int? ind int indexChosen = menuObject.RunMenu("What kind of credential do you want to add?", choices); - if ((indexChosen >= 0) && (indexChosen < choices.Length)) + if (indexChosen >= 0 && indexChosen < choices.Length) { index = indexChosen; return true; @@ -159,7 +159,7 @@ public static bool RunChooseAction(SampleMenu menuObject, out int? index, string int indexChosen = menuObject.RunMenu("How would you want to " + name + " it?", choices); - if ((indexChosen >= 0) && (indexChosen < choices.Length)) + if (indexChosen >= 0 && indexChosen < choices.Length) { index = indexChosen; return true; diff --git a/Yubico.YubiKey/examples/OathSampleCode/YubiKeyOperations/ChooseCredentialProperties.cs b/Yubico.YubiKey/examples/OathSampleCode/YubiKeyOperations/ChooseCredentialProperties.cs index 5c3cd004..072d557a 100644 --- a/Yubico.YubiKey/examples/OathSampleCode/YubiKeyOperations/ChooseCredentialProperties.cs +++ b/Yubico.YubiKey/examples/OathSampleCode/YubiKeyOperations/ChooseCredentialProperties.cs @@ -36,7 +36,7 @@ public static bool RunChooseTypeOption(SampleMenu menuObject, out CredentialType int indexChosen = menuObject.RunMenu("Choose credential type", choices); - if ((indexChosen >= 0) && (indexChosen < choices.Length)) + if (indexChosen >= 0 && indexChosen < choices.Length) { type = _types[choices[indexChosen]]; return true; @@ -60,7 +60,7 @@ public static bool RunChoosePeriodOption(SampleMenu menuObject, out CredentialPe int indexChosen = menuObject.RunMenu("Choose credential period", choices); - if ((indexChosen >= 0) && (indexChosen < choices.Length)) + if (indexChosen >= 0 && indexChosen < choices.Length) { period = _periods[choices[indexChosen]]; return true; @@ -85,7 +85,7 @@ public static bool RunChooseAlgorithmOption(SampleMenu menuObject, out HashAlgor int indexChosen = menuObject.RunMenu("Choose credential algorithm", choices); - if ((indexChosen >= 0) && (indexChosen < choices.Length)) + if (indexChosen >= 0 && indexChosen < choices.Length) { algorithm = _hashAlgorithms[choices[indexChosen]]; return true; @@ -109,7 +109,7 @@ public static bool RunChooseDigitsOption(SampleMenu menuObject, out int? digits) int indexChosen = menuObject.RunMenu("Choose the number of digits in OTP code", choices); - if ((indexChosen >= 0) && (indexChosen < choices.Length)) + if (indexChosen >= 0 && indexChosen < choices.Length) { digits = _digits[choices[indexChosen]]; return true; diff --git a/Yubico.YubiKey/examples/PivSampleCode/CertificateOperations/SampleCertificateOperations.cs b/Yubico.YubiKey/examples/PivSampleCode/CertificateOperations/SampleCertificateOperations.cs index 58e34bf3..240eb6be 100644 --- a/Yubico.YubiKey/examples/PivSampleCode/CertificateOperations/SampleCertificateOperations.cs +++ b/Yubico.YubiKey/examples/PivSampleCode/CertificateOperations/SampleCertificateOperations.cs @@ -16,8 +16,8 @@ using System.Linq; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; -using Yubico.YubiKey.Piv; using Yubico.Core.Tlv; +using Yubico.YubiKey.Piv; namespace Yubico.YubiKey.Sample.PivSampleCode { @@ -192,11 +192,11 @@ public static bool GetSignedCert( // and KeyUsage, and their values are acceptable. int index = 0; int count = 2; - while ((index < signerCert.Extensions.Count) && (count < 2)) + while (index < signerCert.Extensions.Count && count < 2) { if (signerCert.Extensions[index] is X509BasicConstraintsExtension basicConstraints) { - if ((!basicConstraints.CertificateAuthority) || (basicConstraints.PathLengthConstraint < pathLength)) + if (!basicConstraints.CertificateAuthority || basicConstraints.PathLengthConstraint < pathLength) { return false; } @@ -264,8 +264,8 @@ public static bool GetSignedCert( // 04 // where each coordinate is exactly 48 bytes (384 bits) long. HashAlgorithmName signerHash = HashAlgorithmName.SHA256; - if ((string.Equals(signerCert.PublicKey.Oid.FriendlyName, "ECC", StringComparison.Ordinal)) - && (signerCert.PublicKey.EncodedKeyValue.RawData.Length == 97)) + if (string.Equals(signerCert.PublicKey.Oid.FriendlyName, "ECC", StringComparison.Ordinal) + && signerCert.PublicKey.EncodedKeyValue.RawData.Length == 97) { signerHash = HashAlgorithmName.SHA384; } @@ -325,14 +325,14 @@ public static bool GetSignedCert( // Another bit of information to extract from the cert would be the RSA // padding scheme, if the signature algorithm is RSA. However, to avoid // writing a lot more code, this sample always uses PSS. - public static CertificateRequest BuildCertRequestFromDer(byte[] requestDer, HashAlgorithmName signerHash) - { - using AsymmetricAlgorithm requestPublicKey = GetComponentsFromCertRequestDer( - requestDer, - out byte[] _, - out SignatureAlgIdConverter _, - out X500DistinguishedName requestName, - out byte[] _); + public static CertificateRequest BuildCertRequestFromDer(byte[] requestDer, HashAlgorithmName signerHash) + { + using AsymmetricAlgorithm requestPublicKey = GetComponentsFromCertRequestDer( + requestDer, + out byte[] _, + out SignatureAlgIdConverter _, + out X500DistinguishedName requestName, + out byte[] _); if (requestPublicKey is ECDsa ecDsa) { diff --git a/Yubico.YubiKey/examples/PivSampleCode/CertificateOperations/X500NameBuilder.cs b/Yubico.YubiKey/examples/PivSampleCode/CertificateOperations/X500NameBuilder.cs index 491d90c1..f3c675fd 100644 --- a/Yubico.YubiKey/examples/PivSampleCode/CertificateOperations/X500NameBuilder.cs +++ b/Yubico.YubiKey/examples/PivSampleCode/CertificateOperations/X500NameBuilder.cs @@ -131,11 +131,11 @@ public X500DistinguishedName GetDistinguishedName() // the extensions (OID, etc.). public enum X500NameElement { - Country = 0, - State = 1, - Locality = 2, - Organization = 3, - CommonName = 4, + Country = 0, + State = 1, + Locality = 2, + Organization = 3, + CommonName = 4, } public static class X500NameElementExtensions @@ -189,22 +189,22 @@ public static byte[] GetDerEncoding(this X500NameElement nameElement, string val public static byte[] GetOid(this X500NameElement nameElement) => nameElement switch { - X500NameElement.Country => new byte[] { 0x55, 0x04, 0x06 }, - X500NameElement.State => new byte[] { 0x55, 0x04, 0x08 }, - X500NameElement.Locality => new byte[] { 0x55, 0x04, 0x07 }, - X500NameElement.Organization => new byte[] { 0x55, 0x04, 0x0A }, - X500NameElement.CommonName => new byte[] { 0x55, 0x04, 0x03 }, + X500NameElement.Country => new byte[] { 0x55, 0x04, 0x06 }, + X500NameElement.State => new byte[] { 0x55, 0x04, 0x08 }, + X500NameElement.Locality => new byte[] { 0x55, 0x04, 0x07 }, + X500NameElement.Organization => new byte[] { 0x55, 0x04, 0x0A }, + X500NameElement.CommonName => new byte[] { 0x55, 0x04, 0x03 }, _ => throw new ArgumentException(X500NameBuilder.InvalidElementMessage), }; // Is the given length valid for the specified nameElement? public static bool IsValidValueLength(this X500NameElement nameElement, int length) => nameElement switch { - X500NameElement.Country => length == 2, - X500NameElement.State => (length > 0) && (length < 32), - X500NameElement.Locality => (length > 0) && (length < 32), - X500NameElement.Organization => (length > 0) && (length < 64), - X500NameElement.CommonName => (length > 0) && (length < 64), + X500NameElement.Country => length == 2, + X500NameElement.State => length > 0 && length < 32, + X500NameElement.Locality => length > 0 && length < 32, + X500NameElement.Organization => length > 0 && length < 64, + X500NameElement.CommonName => length > 0 && length < 64, _ => throw new ArgumentException(X500NameBuilder.InvalidElementMessage), }; } diff --git a/Yubico.YubiKey/examples/PivSampleCode/Converters/DsaSignatureConverter.cs b/Yubico.YubiKey/examples/PivSampleCode/Converters/DsaSignatureConverter.cs index 7446e164..f703bce5 100644 --- a/Yubico.YubiKey/examples/PivSampleCode/Converters/DsaSignatureConverter.cs +++ b/Yubico.YubiKey/examples/PivSampleCode/Converters/DsaSignatureConverter.cs @@ -14,8 +14,8 @@ using System; using System.Globalization; -using Yubico.YubiKey.Piv; using Yubico.Core.Tlv; +using Yubico.YubiKey.Piv; namespace Yubico.YubiKey.Sample.PivSampleCode { @@ -114,7 +114,7 @@ public static byte[] GetNonStandardDsaFromStandard(byte[] signature, PivAlgorith } } - isValid = ((rValue.Length - offsetR) <= elementLength) && ((sValue.Length - offsetS) <= elementLength); + isValid = rValue.Length - offsetR <= elementLength && sValue.Length - offsetS <= elementLength; } } } @@ -150,7 +150,7 @@ public static byte[] GetNonStandardDsaFromStandard(byte[] signature, PivAlgorith // greater than zero and even. public static byte[] GetStandardDsaFromNonStandard(byte[] signature) { - if ((signature is null) || (signature.Length == 0)) + if (signature is null || signature.Length == 0) { throw new ArgumentNullException(nameof(signature)); } @@ -191,8 +191,8 @@ public static byte[] GetStandardDsaFromNonStandard(byte[] signature) // The first half of the buffer is r, the second is s. // For each element, build an INTEGER: 02 len value. // If the msBit of value is set, prepend a 00 byte. - int startR = ((signature[offsetR] & 0x80) != 0) ? 1 : 0; - int startS = ((signature[offsetS] & 0x80) != 0) ? 1 : 0; + int startR = (signature[offsetR] & 0x80) != 0 ? 1 : 0; + int startS = (signature[offsetS] & 0x80) != 0 ? 1 : 0; byte[] rBuffer = new byte[elementLength + 1]; byte[] sBuffer = new byte[elementLength + 1]; diff --git a/Yubico.YubiKey/examples/PivSampleCode/Converters/KeyConverter.Pem.cs b/Yubico.YubiKey/examples/PivSampleCode/Converters/KeyConverter.Pem.cs index a450b94c..af1dc20e 100644 --- a/Yubico.YubiKey/examples/PivSampleCode/Converters/KeyConverter.Pem.cs +++ b/Yubico.YubiKey/examples/PivSampleCode/Converters/KeyConverter.Pem.cs @@ -305,7 +305,7 @@ private static byte[] GetEncodedKey(char[] pemKeyString, bool isPrivate, out int private static int GetNextTagOffset(byte[] buffer, int offset) { // Make sure there are enough bytes to read. - if ((offset < 0) || (buffer.Length < offset + 2)) + if (offset < 0 || buffer.Length < offset + 2) { return -1; } @@ -321,7 +321,7 @@ private static int GetNextTagOffset(byte[] buffer, int offset) // beyond 83). This says the length is the next 1, 2, or 3 octets. int length = buffer[offset + 1]; int increment = 2; - if ((length == 0x80) || (length > 0x83)) + if (length == 0x80 || length > 0x83) { return -1; } diff --git a/Yubico.YubiKey/examples/PivSampleCode/Converters/PemOperations.cs b/Yubico.YubiKey/examples/PivSampleCode/Converters/PemOperations.cs index 61b94a9a..a9bd9909 100644 --- a/Yubico.YubiKey/examples/PivSampleCode/Converters/PemOperations.cs +++ b/Yubico.YubiKey/examples/PivSampleCode/Converters/PemOperations.cs @@ -185,9 +185,9 @@ 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) { - if (CompareToTarget(pemKeyString, 0, targetStart) == true) + if (CompareToTarget(pemKeyString, 0, targetStart)) { returnValue = CompareToTarget(pemKeyString, pemKeyString.Length - targetEnd.Length, targetEnd); } diff --git a/Yubico.YubiKey/examples/PivSampleCode/Converters/SignatureAlgIdConverter.cs b/Yubico.YubiKey/examples/PivSampleCode/Converters/SignatureAlgIdConverter.cs index 2646b0cf..c882196d 100644 --- a/Yubico.YubiKey/examples/PivSampleCode/Converters/SignatureAlgIdConverter.cs +++ b/Yubico.YubiKey/examples/PivSampleCode/Converters/SignatureAlgIdConverter.cs @@ -264,7 +264,7 @@ private void ReadPssParams(ReadOnlyMemory algIdParams) { if (algIdParams.Length == 2) { - if ((algIdParams.Span[0] == 0x30) && (algIdParams.Span[1] == 0)) + if (algIdParams.Span[0] == 0x30 && algIdParams.Span[1] == 0) { PssSaltLength = 20; } diff --git a/Yubico.YubiKey/examples/PivSampleCode/KeyCollector/SampleKeyCollector.cs b/Yubico.YubiKey/examples/PivSampleCode/KeyCollector/SampleKeyCollector.cs index 2fbf12a2..f1d71021 100644 --- a/Yubico.YubiKey/examples/PivSampleCode/KeyCollector/SampleKeyCollector.cs +++ b/Yubico.YubiKey/examples/PivSampleCode/KeyCollector/SampleKeyCollector.cs @@ -48,7 +48,7 @@ public bool SampleKeyCollectorDelegate(KeyEntryData keyEntryData) return false; } - if (keyEntryData.IsRetry == true) + if (keyEntryData.IsRetry) { if (!(keyEntryData.RetriesRemaining is null)) { @@ -90,20 +90,25 @@ public bool SampleKeyCollectorDelegate(KeyEntryData keyEntryData) break; case KeyEntryRequest.AuthenticatePivManagementKey: - if (keyEntryData.IsRetry == true) + if (keyEntryData.IsRetry) { return false; } - currentValue = CollectValue(DefaultMgmtKeyString, "Management Key (24 bytes in hex, e.g. A1 29 07... or A12907...)"); + + currentValue = CollectValue(DefaultMgmtKeyString, + "Management Key (24 bytes in hex, e.g. A1 29 07... or A12907...)"); break; case KeyEntryRequest.ChangePivManagementKey: - if (keyEntryData.IsRetry == true) + if (keyEntryData.IsRetry) { return false; } - currentValue = CollectValue(DefaultMgmtKeyString, "Current Management Key (24 bytes in hex, e.g. A1 29 07... or A12907...)"); - newValue = CollectValue(DefaultMgmtKeyString, "New Management Key (24 bytes in hex, e.g. A1 29 07... or A12907...)"); + + currentValue = CollectValue(DefaultMgmtKeyString, + "Current Management Key (24 bytes in hex, e.g. A1 29 07... or A12907...)"); + newValue = CollectValue(DefaultMgmtKeyString, + "New Management Key (24 bytes in hex, e.g. A1 29 07... or A12907...)"); break; } @@ -128,7 +133,8 @@ private bool GetUserInputOnRetries(KeyEntryData keyEntryData) } string title = keyEntryData.RetriesRemaining + " tries remaining, continue?"; - string[] menuItems = new string[] { + string[] menuItems = new string[] + { "Yes, try again", "No, cancel operation" }; @@ -146,13 +152,14 @@ public static byte[] CollectValue(string defaultValueString, string name) SampleMenu.WriteMessage(MessageType.Title, 0, "Enter D for default value (" + defaultValueString + ")"); char[] collectedValue = SampleMenu.ReadResponse(out int _); - if ((collectedValue.Length == 1) && (collectedValue[0] == 'D')) + if (collectedValue.Length == 1 && collectedValue[0] == 'D') { return defaultValueString switch { DefaultPinString => new byte[] { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36 }, DefaultPukString => new byte[] { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38 }, - DefaultMgmtKeyString => new byte[] { + DefaultMgmtKeyString => 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 @@ -188,6 +195,7 @@ private static byte[] ConvertCharArrayToByteArray(string valueType, char[] value break; } } + indexV++; } diff --git a/Yubico.YubiKey/examples/PivSampleCode/Run/PivSampleRun.Operations.cs b/Yubico.YubiKey/examples/PivSampleCode/Run/PivSampleRun.Operations.cs index 200719bf..32dd7c64 100644 --- a/Yubico.YubiKey/examples/PivSampleCode/Run/PivSampleRun.Operations.cs +++ b/Yubico.YubiKey/examples/PivSampleCode/Run/PivSampleRun.Operations.cs @@ -14,10 +14,10 @@ using System; using System.Linq; -using Yubico.YubiKey.Sample.SharedCode; -using Yubico.YubiKey.Piv; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; +using Yubico.YubiKey.Piv; +using Yubico.YubiKey.Sample.SharedCode; namespace Yubico.YubiKey.Sample.PivSampleCode { @@ -178,7 +178,7 @@ public bool RunRecoverPinOnlyMode() SampleMenu.WriteMessage(MessageType.Title, 0, "overwritten. The result is the PivPinOnly mode of the YubiKey"); SampleMenu.WriteMessage(MessageType.Title, 0, "after recovery.\n"); if (PinOnlyMode.RunRecoverPivPinOnlyMode( - _yubiKeyChosen, _keyCollector.SampleKeyCollectorDelegate, out PivPinOnlyMode mode)) + _yubiKeyChosen, _keyCollector.SampleKeyCollectorDelegate, out PivPinOnlyMode mode)) { SampleMenu.WriteMessage(MessageType.Title, 0, "PIN-only mode: " + mode.ToString() + "\n"); return true; @@ -661,7 +661,7 @@ private static bool GetAsymmetricSlotNumber(out byte slotNumber) { return false; } - if ((valueChars[0] != '8') && (valueChars[0] != '9')) + if (valueChars[0] != '8' && valueChars[0] != '9') { return false; } @@ -672,13 +672,13 @@ private static bool GetAsymmetricSlotNumber(out byte slotNumber) hiVal = (byte)((hiVal - subVal) << 4); - if ((valueChars[1] < '0') || (valueChars[1] > '9')) + if (valueChars[1] < '0' || valueChars[1] > '9') { subVal = 0x37; - if ((valueChars[1] < 'A') || (valueChars[1] > 'F')) + if (valueChars[1] < 'A' || valueChars[1] > 'F') { subVal = 0x57; - if ((valueChars[1] < 'a') || (valueChars[1] > 'f')) + if (valueChars[1] < 'a' || valueChars[1] > 'f') { return false; } @@ -688,11 +688,11 @@ private static bool GetAsymmetricSlotNumber(out byte slotNumber) loVal -= subVal; slotNumber = (byte)(hiVal + loVal); - if ((slotNumber < 0x82) || (slotNumber > 0x9E)) + if (slotNumber < 0x82 || slotNumber > 0x9E) { return false; } - if ((slotNumber > 0x95) && (slotNumber < 0x9A)) + if (slotNumber > 0x95 && slotNumber < 0x9A) { return false; } @@ -769,12 +769,12 @@ private static bool GetNewRetryCounts(out byte newRetryCountPin, out byte newRet SampleMenu.WriteMessage(MessageType.Title, 0, "PIN retry count? (1 to 255)"); _ = SampleMenu.ReadResponse(out int response); - if ((response != 0) && (response <= 255)) + if (response != 0 && response <= 255) { newRetryCountPin = (byte)response; SampleMenu.WriteMessage(MessageType.Title, 0, "PUK retry count? (1 to 255)"); _ = SampleMenu.ReadResponse(out response); - if ((response != 0) && (response <= 255)) + if (response != 0 && response <= 255) { newRetryCountPuk = (byte)response; return true; diff --git a/Yubico.YubiKey/examples/PivSampleCode/SlotContents/SamplePivSlotContents.cs b/Yubico.YubiKey/examples/PivSampleCode/SlotContents/SamplePivSlotContents.cs index b9613390..5ec0c8b2 100644 --- a/Yubico.YubiKey/examples/PivSampleCode/SlotContents/SamplePivSlotContents.cs +++ b/Yubico.YubiKey/examples/PivSampleCode/SlotContents/SamplePivSlotContents.cs @@ -14,8 +14,8 @@ using System; using System.Security.Cryptography.X509Certificates; -using Yubico.YubiKey.Sample.SharedCode; using Yubico.YubiKey.Piv; +using Yubico.YubiKey.Sample.SharedCode; namespace Yubico.YubiKey.Sample.PivSampleCode { diff --git a/Yubico.YubiKey/examples/PivSampleCode/YubiKeyOperations/ChangeSecret.cs b/Yubico.YubiKey/examples/PivSampleCode/YubiKeyOperations/ChangeSecret.cs index 3e663d89..6b16cabe 100644 --- a/Yubico.YubiKey/examples/PivSampleCode/YubiKeyOperations/ChangeSecret.cs +++ b/Yubico.YubiKey/examples/PivSampleCode/YubiKeyOperations/ChangeSecret.cs @@ -13,8 +13,8 @@ // limitations under the License. using System; -using Yubico.YubiKey.Sample.SharedCode; using Yubico.YubiKey.Piv; +using Yubico.YubiKey.Sample.SharedCode; namespace Yubico.YubiKey.Sample.PivSampleCode { diff --git a/Yubico.YubiKey/examples/PivSampleCode/YubiKeyOperations/KeyPairs.cs b/Yubico.YubiKey/examples/PivSampleCode/YubiKeyOperations/KeyPairs.cs index f189b39c..cc04d5a1 100644 --- a/Yubico.YubiKey/examples/PivSampleCode/YubiKeyOperations/KeyPairs.cs +++ b/Yubico.YubiKey/examples/PivSampleCode/YubiKeyOperations/KeyPairs.cs @@ -13,8 +13,8 @@ // limitations under the License. using System; -using Yubico.YubiKey.Piv; using System.Security.Cryptography.X509Certificates; +using Yubico.YubiKey.Piv; namespace Yubico.YubiKey.Sample.PivSampleCode { @@ -41,10 +41,10 @@ public static bool RunGenerateKeyPair( slotContents = new SamplePivSlotContents() { SlotNumber = slotNumber, - Algorithm = algorithm, - PinPolicy = pinPolicy, - TouchPolicy = touchPolicy, - PublicKey = pivPublicKey, + Algorithm = algorithm, + PinPolicy = pinPolicy, + TouchPolicy = touchPolicy, + PublicKey = pivPublicKey, }; } diff --git a/Yubico.YubiKey/examples/PivSampleCode/YubiKeyOperations/PinOnlyMode.cs b/Yubico.YubiKey/examples/PivSampleCode/YubiKeyOperations/PinOnlyMode.cs index f026f68c..c3c67e4e 100644 --- a/Yubico.YubiKey/examples/PivSampleCode/YubiKeyOperations/PinOnlyMode.cs +++ b/Yubico.YubiKey/examples/PivSampleCode/YubiKeyOperations/PinOnlyMode.cs @@ -13,8 +13,8 @@ // limitations under the License. using System; -using Yubico.YubiKey.Sample.SharedCode; using Yubico.YubiKey.Piv; +using Yubico.YubiKey.Sample.SharedCode; namespace Yubico.YubiKey.Sample.PivSampleCode { diff --git a/Yubico.YubiKey/examples/PivSampleCode/YubiKeyOperations/PrivateKeyOperations.cs b/Yubico.YubiKey/examples/PivSampleCode/YubiKeyOperations/PrivateKeyOperations.cs index 0bce1ae5..1da57695 100644 --- a/Yubico.YubiKey/examples/PivSampleCode/YubiKeyOperations/PrivateKeyOperations.cs +++ b/Yubico.YubiKey/examples/PivSampleCode/YubiKeyOperations/PrivateKeyOperations.cs @@ -14,8 +14,8 @@ using System; using System.Security.Cryptography; -using Yubico.YubiKey.Piv; using Yubico.YubiKey.Cryptography; +using Yubico.YubiKey.Piv; namespace Yubico.YubiKey.Sample.PivSampleCode { @@ -94,7 +94,7 @@ public static bool RunSignData( digest = RsaFormat.FormatPkcs1Sign(digest, digestAlgorithm, keySizeBits); } } - + using (var pivSession = new PivSession(yubiKey)) { pivSession.KeyCollector = KeyCollectorDelegate; @@ -167,11 +167,11 @@ public static bool RunKeyAgree( PivPublicKey correspondentPublicKey, out byte[] computedSecret) { - using (var pivSession = new PivSession(yubiKey)) - { - pivSession.KeyCollector = KeyCollectorDelegate; - computedSecret = pivSession.KeyAgree(slotNumber, correspondentPublicKey); - } + using (var pivSession = new PivSession(yubiKey)) + { + pivSession.KeyCollector = KeyCollectorDelegate; + computedSecret = pivSession.KeyAgree(slotNumber, correspondentPublicKey); + } return true; } diff --git a/Yubico.YubiKey/examples/SharedSampleCode/Menu/SampleMenu.cs b/Yubico.YubiKey/examples/SharedSampleCode/Menu/SampleMenu.cs index 88aa4545..1fa23605 100644 --- a/Yubico.YubiKey/examples/SharedSampleCode/Menu/SampleMenu.cs +++ b/Yubico.YubiKey/examples/SharedSampleCode/Menu/SampleMenu.cs @@ -55,7 +55,7 @@ public class SampleMenu public SampleMenu(int maxInvalidCount, Type mainMenuEnumType, int exitValue) { _maxInvalidCount = DefaultMaxInvalidCount; - if ((maxInvalidCount >= LowMaxInvalidCount) && (maxInvalidCount <= HighMaxInvalidCount)) + if (maxInvalidCount >= LowMaxInvalidCount && maxInvalidCount <= HighMaxInvalidCount) { _maxInvalidCount = maxInvalidCount; } @@ -75,7 +75,7 @@ public SampleMenu(int maxInvalidCount, Type mainMenuEnumType, int exitValue) public int RunMainMenu(string title) { int indexChosen = RunMenu(title, _mainMenuStrings); - if ((indexChosen >= 0) && (indexChosen < _mainMenuStrings.Length)) + if (indexChosen >= 0 && indexChosen < _mainMenuStrings.Length) { object? returnValue = _mainMenuValues.GetValue(indexChosen); if (!(returnValue is null)) @@ -118,7 +118,7 @@ public int RunMenu(string title, string[] menuItems) } _ = ReadResponse(out int response); - if ((response > 0) && (response <= menuItems.Length)) + if (response > 0 && response <= menuItems.Length) { // When writing the menu, counting begins at 1. So to get the // index of the choice, subtract 1. diff --git a/Yubico.YubiKey/examples/SharedSampleCode/YubiKeyOperations/ChooseYubiKey.cs b/Yubico.YubiKey/examples/SharedSampleCode/YubiKeyOperations/ChooseYubiKey.cs index 905d78e2..072e4199 100644 --- a/Yubico.YubiKey/examples/SharedSampleCode/YubiKeyOperations/ChooseYubiKey.cs +++ b/Yubico.YubiKey/examples/SharedSampleCode/YubiKeyOperations/ChooseYubiKey.cs @@ -14,8 +14,8 @@ using System; using System.Collections.Generic; -using System.Linq; using System.Globalization; +using System.Linq; namespace Yubico.YubiKey.Sample.SharedCode { @@ -84,7 +84,7 @@ public static bool RunChooseYubiKey( for (int index = 0; index < yubiKeyArray.Length; index++) { if (!(yubiKeyArray[index].SerialNumber is null) - && (yubiKeyChosen.SerialNumber == yubiKeyArray[index].SerialNumber)) + && yubiKeyChosen.SerialNumber == yubiKeyArray[index].SerialNumber) { return true; } @@ -96,7 +96,7 @@ public static bool RunChooseYubiKey( // return value to null. yubiKeyChosen = null; - if ((yubiKeyArray.Length == 1) && (alwaysAsk == false)) + if (yubiKeyArray.Length == 1 && alwaysAsk == false) { yubiKeyChosen = yubiKeyArray[0]; return true; @@ -112,7 +112,7 @@ public static bool RunChooseYubiKey( } int indexChosen = menuObject.RunMenu("Which YubiKey do you want to use?", choices); - if ((indexChosen >= 0) && (indexChosen < yubiKeyArray.Length)) + if (indexChosen >= 0 && indexChosen < yubiKeyArray.Length) { yubiKeyChosen = yubiKeyArray[indexChosen]; return true; diff --git a/Yubico.YubiKey/examples/SharedSampleCode/YubiKeyOperations/ListYubiKeys.cs b/Yubico.YubiKey/examples/SharedSampleCode/YubiKeyOperations/ListYubiKeys.cs index 4fc35fcb..ff0b8004 100644 --- a/Yubico.YubiKey/examples/SharedSampleCode/YubiKeyOperations/ListYubiKeys.cs +++ b/Yubico.YubiKey/examples/SharedSampleCode/YubiKeyOperations/ListYubiKeys.cs @@ -13,8 +13,8 @@ // limitations under the License. using System.Collections.Generic; -using System.Linq; using System.Globalization; +using System.Linq; using Yubico.YubiKey; namespace Yubico.YubiKey.Sample.SharedCode diff --git a/Yubico.YubiKey/examples/U2fSampleCode/KeyCollector/U2fSampleKeyCollector.cs b/Yubico.YubiKey/examples/U2fSampleCode/KeyCollector/U2fSampleKeyCollector.cs index c2dc50f7..ec4a97d2 100644 --- a/Yubico.YubiKey/examples/U2fSampleCode/KeyCollector/U2fSampleKeyCollector.cs +++ b/Yubico.YubiKey/examples/U2fSampleCode/KeyCollector/U2fSampleKeyCollector.cs @@ -24,16 +24,16 @@ namespace Yubico.YubiKey.Sample.U2fSampleCode // not allow for retries. public class U2fSampleKeyCollector { - // This allows the caller to specify what the operation is. - // Before calling an SDK method that will call the KeyCollector. Set this - // property so the KeyCollector knows what message to report. - public U2fKeyCollectorOperation Operation { get; set; } - public U2fSampleKeyCollector() { Operation = U2fKeyCollectorOperation.None; } + // This allows the caller to specify what the operation is. + // Before calling an SDK method that will call the KeyCollector. Set this + // property so the KeyCollector knows what message to report. + public U2fKeyCollectorOperation Operation { get; set; } + public bool U2fSampleKeyCollectorDelegate(KeyEntryData keyEntryData) { if (keyEntryData is null) @@ -41,7 +41,7 @@ public bool U2fSampleKeyCollectorDelegate(KeyEntryData keyEntryData) return false; } - if (keyEntryData.IsRetry == true) + if (keyEntryData.IsRetry) { return false; } @@ -59,11 +59,13 @@ public bool U2fSampleKeyCollectorDelegate(KeyEntryData keyEntryData) case KeyEntryRequest.TouchRequest: ReportOperation(); - SampleMenu.WriteMessage(MessageType.Title, 0, "touch the YubiKey's contact to complete the operation.\n"); + SampleMenu.WriteMessage(MessageType.Title, 0, + "touch the YubiKey's contact to complete the operation.\n"); return true; case KeyEntryRequest.SetU2fPin: - SampleMenu.WriteMessage(MessageType.Title, 0, "Setting the U2F application on the YubiKey to have a PIN, enter the PIN."); + SampleMenu.WriteMessage(MessageType.Title, 0, + "Setting the U2F application on the YubiKey to have a PIN, enter the PIN."); collectedValue = SampleMenu.ReadResponse(out int _); pinValue = ConvertCharArrayToByteArray(collectedValue); keyEntryData.SubmitValue(pinValue); @@ -74,12 +76,14 @@ public bool U2fSampleKeyCollectorDelegate(KeyEntryData keyEntryData) case KeyEntryRequest.VerifyU2fPin: if (Operation == U2fKeyCollectorOperation.Register) { - SampleMenu.WriteMessage(MessageType.Title, 0, "Enter the PIN in order to complete registration."); + SampleMenu.WriteMessage(MessageType.Title, 0, + "Enter the PIN in order to complete registration."); } else { SampleMenu.WriteMessage(MessageType.Title, 0, "Enter the PIN in order to verify."); } + collectedValue = SampleMenu.ReadResponse(out int _); pinValue = ConvertCharArrayToByteArray(collectedValue); keyEntryData.SubmitValue(pinValue); @@ -113,15 +117,18 @@ private void ReportOperation() break; case U2fKeyCollectorOperation.Register: - SampleMenu.WriteMessage(MessageType.Title, 0, "The YubiKey is trying to register a U2F credential,"); + SampleMenu.WriteMessage(MessageType.Title, 0, + "The YubiKey is trying to register a U2F credential,"); break; case U2fKeyCollectorOperation.Authenticate: - SampleMenu.WriteMessage(MessageType.Title, 0, "The YubiKey is trying to authenticate a U2F credential,"); + SampleMenu.WriteMessage(MessageType.Title, 0, + "The YubiKey is trying to authenticate a U2F credential,"); break; case U2fKeyCollectorOperation.Reset: - SampleMenu.WriteMessage(MessageType.Title, 0, "The YubiKey is trying to reset the U2F application,"); + SampleMenu.WriteMessage(MessageType.Title, 0, + "The YubiKey is trying to reset the U2F application,"); break; } } diff --git a/Yubico.YubiKey/examples/U2fSampleCode/Run/U2fSampleRun.Operations.cs b/Yubico.YubiKey/examples/U2fSampleCode/Run/U2fSampleRun.Operations.cs index 12225b2c..6f483c54 100644 --- a/Yubico.YubiKey/examples/U2fSampleCode/Run/U2fSampleRun.Operations.cs +++ b/Yubico.YubiKey/examples/U2fSampleCode/Run/U2fSampleRun.Operations.cs @@ -14,10 +14,10 @@ using System; using System.Linq; +using System.Security.Cryptography; +using Yubico.YubiKey.Cryptography; using Yubico.YubiKey.Sample.SharedCode; using Yubico.YubiKey.U2f; -using Yubico.YubiKey.Cryptography; -using System.Security.Cryptography; namespace Yubico.YubiKey.Sample.U2fSampleCode { @@ -288,9 +288,9 @@ public bool RunReset() { string versionNumber = _yubiKeyChosen.FirmwareVersion.ToString(); - if ((_yubiKeyChosen.FirmwareVersion >= new FirmwareVersion(5, 0, 0)) - || (_yubiKeyChosen.FirmwareVersion < new FirmwareVersion(4, 0, 0)) - || (!_yubiKeyChosen.IsFipsSeries)) + if (_yubiKeyChosen.FirmwareVersion >= new FirmwareVersion(5, 0, 0) + || _yubiKeyChosen.FirmwareVersion < new FirmwareVersion(4, 0, 0) + || !_yubiKeyChosen.IsFipsSeries) { SampleMenu.WriteMessage(MessageType.Title, 0, "It is possible to reset the U2F application on only version 4"); SampleMenu.WriteMessage(MessageType.Title, 0, "FIPS series YubiKeys."); diff --git a/Yubico.YubiKey/examples/U2fSampleCode/YubiKeyOperations/U2fFips.cs b/Yubico.YubiKey/examples/U2fSampleCode/YubiKeyOperations/U2fFips.cs index 448d1779..317bbc1c 100644 --- a/Yubico.YubiKey/examples/U2fSampleCode/YubiKeyOperations/U2fFips.cs +++ b/Yubico.YubiKey/examples/U2fSampleCode/YubiKeyOperations/U2fFips.cs @@ -26,7 +26,7 @@ public static class U2fFips public static bool GetFipsMode(IYubiKeyDevice yubiKey, out bool isFipsMode) { isFipsMode = false; - if ((yubiKey is null) || (!yubiKey.IsFipsSeries)) + if (yubiKey is null || !yubiKey.IsFipsSeries) { return false; } diff --git a/Yubico.YubiKey/examples/U2fSampleCode/YubiKeyOperations/U2fReset.cs b/Yubico.YubiKey/examples/U2fSampleCode/YubiKeyOperations/U2fReset.cs index f2e94169..bc4362d7 100644 --- a/Yubico.YubiKey/examples/U2fSampleCode/YubiKeyOperations/U2fReset.cs +++ b/Yubico.YubiKey/examples/U2fSampleCode/YubiKeyOperations/U2fReset.cs @@ -13,12 +13,12 @@ // limitations under the License. using System; +using System.Diagnostics; using System.Globalization; using System.Threading; using System.Threading.Tasks; -using System.Diagnostics; -using Yubico.YubiKey.U2f.Commands; using Yubico.YubiKey.Sample.SharedCode; +using Yubico.YubiKey.U2f.Commands; namespace Yubico.YubiKey.Sample.U2fSampleCode { diff --git a/Yubico.YubiKey/src/AssemblyInfo.cs b/Yubico.YubiKey/src/AssemblyInfo.cs index b1da9f09..a8b816ed 100644 --- a/Yubico.YubiKey/src/AssemblyInfo.cs +++ b/Yubico.YubiKey/src/AssemblyInfo.cs @@ -14,4 +14,4 @@ using System; -[assembly:CLSCompliant(true)] +[assembly: CLSCompliant(true)] diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/CcidConnection.cs b/Yubico.YubiKey/src/Yubico/YubiKey/CcidConnection.cs index ec31432d..b9eb6eca 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/CcidConnection.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/CcidConnection.cs @@ -14,14 +14,13 @@ using System; using System.Globalization; +using System.Linq; using Yubico.Core.Buffers; -using Yubico.YubiKey.InterIndustry.Commands; -using Yubico.YubiKey.Pipelines; -using Yubico.YubiKey.Scp03; using Yubico.Core.Devices.SmartCard; using Yubico.Core.Iso7816; using Yubico.Core.Logging; -using System.Linq; +using Yubico.YubiKey.InterIndustry.Commands; +using Yubico.YubiKey.Pipelines; namespace Yubico.YubiKey { @@ -39,7 +38,7 @@ internal class CcidConnection : IYubiKeyConnection protected CcidConnection(ISmartCardDevice smartCardDevice, YubiKeyApplication application, byte[]? applicationId) { - if ((applicationId is null) && (application == YubiKeyApplication.Unknown)) + if (applicationId is null && application == YubiKeyApplication.Unknown) { throw new NotSupportedException(); } diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/ConnectionManager.cs b/Yubico.YubiKey/src/Yubico/YubiKey/ConnectionManager.cs index 8d2d8810..aca9824c 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/ConnectionManager.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/ConnectionManager.cs @@ -43,9 +43,9 @@ namespace Yubico.YubiKey // JUSTIFICATION: This class is a singleton, which means its lifetime will span the process lifetime. It contains // a lock which is disposable, so we must call its Dispose method at some point. The only reasonable time to do that // is in this class's finalizer. This analyzer doesn't seem to see this and still warns. - #pragma warning disable CA1001 +#pragma warning disable CA1001 internal class ConnectionManager - #pragma warning restore CA1001 +#pragma warning restore CA1001 { // Easy thread-safe singleton pattern using Lazy<> private static readonly Lazy _instance = @@ -318,5 +318,5 @@ public void EndConnection(IYubiKeyDevice yubiKeyDevice) _hashSetLock.ExitWriteLock(); } } - } + } } diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Cryptography/EcdsaVerify.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Cryptography/EcdsaVerify.cs index 3921b388..3763e095 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Cryptography/EcdsaVerify.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Cryptography/EcdsaVerify.cs @@ -16,8 +16,8 @@ using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using Yubico.Core.Tlv; -using Yubico.YubiKey.Piv; using Yubico.YubiKey.Fido2.Cose; +using Yubico.YubiKey.Piv; namespace Yubico.YubiKey.Cryptography { @@ -184,7 +184,7 @@ public EcdsaVerify(PivPublicKey pivPublicKey) throw new ArgumentNullException(nameof(pivPublicKey)); } - ReadOnlySpan pubPoint = (pivPublicKey is PivEccPublicKey eccKey) + ReadOnlySpan pubPoint = pivPublicKey is PivEccPublicKey eccKey ? eccKey.PublicPoint : ReadOnlySpan.Empty; ECDsa = ConvertPublicKey(pubPoint.ToArray()); @@ -365,7 +365,7 @@ private static ECDsa ConvertPublicKey(ReadOnlyMemory encodedEccPoint) byte[] xCoordinate = Array.Empty(); byte[] yCoordinate = Array.Empty(); - if ((encodedEccPoint.Length >= MinEncodedPointLength) && (encodedEccPoint.Span[0] == EncodedPointTag)) + if (encodedEccPoint.Length >= MinEncodedPointLength && encodedEccPoint.Span[0] == EncodedPointTag) { int coordLength = (encodedEccPoint.Length - 1) / 2; xCoordinate = encodedEccPoint.Slice(1, coordLength).ToArray(); @@ -412,9 +412,9 @@ private static ECDsa CheckECDsa(ECDsa toCheck) _ => -1, }; - if ((eccParams.Q.X.Length > 0) && (eccParams.Q.X.Length <= coordinateLength)) + if (eccParams.Q.X.Length > 0 && eccParams.Q.X.Length <= coordinateLength) { - if ((eccParams.Q.Y.Length > 0) && (eccParams.Q.Y.Length <= coordinateLength)) + if (eccParams.Q.Y.Length > 0 && eccParams.Q.Y.Length <= coordinateLength) { return toCheck; } @@ -474,7 +474,7 @@ private static bool TryCopyNextInteger(TlvReader tlvReader, Memory signatu } // If we still have data and it is not too long, copy - if ((length > 0) && (length <= coordinateLength)) + if (length > 0 && length <= coordinateLength) { rsValue[index..].CopyTo(signatureValue[(coordinateLength - length)..]); return true; diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Cryptography/RsaFormat.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Cryptography/RsaFormat.cs index 5b9edfbb..70406411 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Cryptography/RsaFormat.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Cryptography/RsaFormat.cs @@ -14,8 +14,8 @@ using System; using System.Globalization; -using System.Security.Cryptography; using System.Runtime.CompilerServices; +using System.Security.Cryptography; using Yubico.Core.Tlv; namespace Yubico.YubiKey.Cryptography @@ -264,13 +264,13 @@ public static bool TryParsePkcs1Verify(ReadOnlySpan formattedSignature, digestAlgorithm = 0; digest = Array.Empty(); - if ((formattedSignature.Length != 128) && (formattedSignature.Length != 256)) + if (formattedSignature.Length != 128 && formattedSignature.Length != 256) { return false; } // We expect to find 00 01 FF ... FF 00 - if ((formattedSignature[0] != Pkcs1LeadByte) || (formattedSignature[1] != Pkcs1SignByte)) + if (formattedSignature[0] != Pkcs1LeadByte || formattedSignature[1] != Pkcs1SignByte) { return false; } @@ -664,7 +664,7 @@ public static bool TryParsePkcs1Pss(ReadOnlySpan formattedSignature, mPrimeAndH = Array.Empty(); isVerified = false; - if ((formattedSignature.Length != 128) && (formattedSignature.Length != 256)) + if (formattedSignature.Length != 128 && formattedSignature.Length != 256) { return false; } @@ -716,7 +716,7 @@ public static bool TryParsePkcs1Pss(ReadOnlySpan formattedSignature, // Verify that all PS bytes are 0, and that the byte after PS is 01. int index = Array.FindIndex(buffer, p => p != 0); - if ((index != psLength) || (buffer[psLength] != 1)) + if (index != psLength || buffer[psLength] != 1) { return false; } @@ -843,7 +843,7 @@ public static byte[] FormatPkcs1Encrypt(ReadOnlySpan inputData, int keySiz // There must be at least 8 bytes of pad, plus 3 extra bytes, the // leading 00 02, then the separator between pad and data: 00. If // there's too much data, we can't format. - if ((inputData.Length == 0) || (inputData.Length > buffer.Length - (Pkcs1MinPadLength + 3))) + if (inputData.Length == 0 || inputData.Length > buffer.Length - (Pkcs1MinPadLength + 3)) { throw new ArgumentException( string.Format( @@ -932,7 +932,7 @@ public static bool TryParsePkcs1Decrypt(ReadOnlySpan formattedData, out by // Return this buffer if there is any error. outputData = Array.Empty(); - if ((formattedData.Length != 128) && (formattedData.Length != 256)) + if (formattedData.Length != 128 && formattedData.Length != 256) { return false; } @@ -963,7 +963,7 @@ public static bool TryParsePkcs1Decrypt(ReadOnlySpan formattedData, out by // byte was 0 (startIndex will be 0), or if the zero byte does not // allow for more than 8 pad bytes (startIndex will be < 10), this is // an error. - if (startIndex < (Pkcs1MinPadLength + 2)) + if (startIndex < Pkcs1MinPadLength + 2) { errorFlag |= 1; } @@ -1095,7 +1095,7 @@ public static byte[] FormatPkcs1Oaep(ReadOnlySpan inputData, int digestAlg int digestLength = digester.HashSize / 8; - if ((inputData.Length == 0) || (inputData.Length > (buffer.Length - ((2 * digestLength) + 2)))) + if (inputData.Length == 0 || inputData.Length > buffer.Length - ((2 * digestLength) + 2)) { throw new ArgumentException( string.Format( @@ -1376,7 +1376,7 @@ private static int BuildDigestInfo(ReadOnlySpan digest, int digestAlgorith // If the digest.Length is not digestLength, either isValid will be // false or the outputLength won't be totalLength. So this is where // digest.Length is checked. - if ((isValid == false) || (outputLength != totalLength)) + if (isValid == false || outputLength != totalLength) { throw new ArgumentException( string.Format( @@ -1504,7 +1504,7 @@ private static bool TryParseOid(bool isValid, bool sameOid = oid.Span.SequenceEqual(new Span(supportedOid)); - if ((sameOid == false) || (digest.Length != digestLength) || (oidParams.Length != 0)) + if (sameOid == false || digest.Length != digestLength || oidParams.Length != 0) { returnValue = false; } diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/AuthenticatorData.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/AuthenticatorData.cs index 6f54906a..2f86af2f 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/AuthenticatorData.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/AuthenticatorData.cs @@ -13,8 +13,8 @@ // limitations under the License. using System; -using System.Collections.Generic; using System.Buffers.Binary; +using System.Collections.Generic; using System.Formats.Cbor; using Yubico.YubiKey.Fido2.Cose; using Yubico.YubiKey.Fido2.PinProtocols; @@ -191,7 +191,7 @@ public AuthenticatorData(ReadOnlyMemory encodedData) // determines that the caller is not allowed to get that data or it // is not available. So don't try to read any extensions unless we // know for sure there is data to read. - if (extensions && (offset < EncodedAuthenticatorData.Length)) + if (extensions && offset < EncodedAuthenticatorData.Length) { var extensionList = new Dictionary(); var cbor = new CborReader(EncodedAuthenticatorData[offset..], CborConformanceMode.Ctap2Canonical); @@ -290,7 +290,7 @@ public byte[] GetCredBlobExtension() /// used to create the /// GetAssertion parameters. /// - /// + /// /// If you are getting assertions using /// , you can use the /// property. @@ -364,7 +364,7 @@ public CredProtectPolicy GetCredProtectExtension() if (Extensions.ContainsKey(KeyCredProtect)) { byte[] encodedValue = Extensions[KeyCredProtect]; - if ((encodedValue.Length == 1) && (encodedValue[0] >= 1) && (encodedValue[0] <= 3)) + if (encodedValue.Length == 1 && encodedValue[0] >= 1 && encodedValue[0] <= 3) { return (CredProtectPolicy)encodedValue[0]; } diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/AuthenticatorInfo.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/AuthenticatorInfo.cs index 7c90387c..2fbfacdc 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/AuthenticatorInfo.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/AuthenticatorInfo.cs @@ -13,10 +13,10 @@ // limitations under the License. using System; -using System.Linq; +using System.Collections.Generic; using System.Formats.Cbor; using System.Globalization; -using System.Collections.Generic; +using System.Linq; using Yubico.YubiKey.Fido2.Cbor; using Yubico.YubiKey.Fido2.Cose; using Yubico.YubiKey.Fido2.PinProtocols; @@ -136,7 +136,7 @@ public class AuthenticatorInfo /// This property is OPTIONAL, and if the YubiKey provides no value, this /// will be null. /// - public IReadOnlyDictionary? Options {get; private set; } + public IReadOnlyDictionary? Options { get; private set; } /// /// The maximum size, in bytes, of a message sent to the YubiKey. @@ -329,7 +329,7 @@ public AuthenticatorInfo(ReadOnlyMemory cborEncoding) Aaguid = new ReadOnlyMemory(_aaguid); if (cborMap.Contains(KeyExtensions)) { - Extensions = (IReadOnlyList)cborMap.ReadArray(KeyExtensions); + Extensions = cborMap.ReadArray(KeyExtensions); } if (cborMap.Contains(KeyOptions)) { diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/AuthenticatorOptions.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/AuthenticatorOptions.cs index e4645149..21c8c73a 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/AuthenticatorOptions.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/AuthenticatorOptions.cs @@ -176,33 +176,30 @@ public static OptionValue GetDefaultOptionValue(string option) { switch (option) { - default: - return OptionValue.Unknown; - - case "plat": - case "rk": - case "noMcGaPermissionsWithClientPin": - case "makeCredUvNotRqd": + case plat: + case rk: + case noMcGaPermissionsWithClientPin: + case makeCredUvNotRqd: return OptionValue.False; - - case "up": + case up: return OptionValue.True; - - case "clientPin": - case "uv": - case "pinUvAuthToken": - case "largeBlobs": - case "ep": - case "bioEnroll": - case "userVerificationMgmtPreview": - case "uvBioEnroll": - case "authnrCfg": - case "uvAcfg": - case "credMgmt": - case "credentialMgmtPreview": - case "setMinPINLength": - case "alwaysUv": + case clientPin: + case uv: + case pinUvAuthToken: + case largeBlobs: + case ep: + case bioEnroll: + case userVerificationMgmtPreview: + case uvBioEnroll: + case authnrCfg: + case uvAcfg: + case credMgmt: + case credentialMgmtPreview: + case setMinPINLength: + case alwaysUv: return OptionValue.NotSupported; + default: + return OptionValue.Unknown; } } } diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/AuthenticatorTransports.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/AuthenticatorTransports.cs index 02fa1f3f..03491a02 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/AuthenticatorTransports.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/AuthenticatorTransports.cs @@ -13,9 +13,9 @@ // limitations under the License. using System; -using System.Globalization; using System.Collections.Generic; using System.Formats.Cbor; +using System.Globalization; using Yubico.YubiKey.Fido2.Cbor; namespace Yubico.YubiKey.Fido2 diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Cbor/CborHelpers.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Cbor/CborHelpers.cs index 67b1da3d..52cff753 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Cbor/CborHelpers.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Cbor/CborHelpers.cs @@ -104,7 +104,7 @@ internal static class CborHelpers /// public static byte[] EncodeStringArray(IReadOnlyList? localData) { - if ((localData is null) || (localData.Count == 0)) + if (localData is null || localData.Count == 0) { return Array.Empty(); } @@ -141,7 +141,7 @@ public static byte[] EncodeStringArray(IReadOnlyList? localData) /// public static byte[] EncodeArrayOfObjects(IReadOnlyList? localData) { - if ((localData is null) || (localData.Count == 0)) + if (localData is null || localData.Count == 0) { return Array.Empty(); } diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Cbor/CborMap.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Cbor/CborMap.cs index 9e2303f6..147ff45b 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Cbor/CborMap.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Cbor/CborMap.cs @@ -13,9 +13,9 @@ // limitations under the License. using System; -using System.Globalization; using System.Collections.Generic; using System.Formats.Cbor; +using System.Globalization; namespace Yubico.YubiKey.Fido2.Cbor { @@ -98,9 +98,9 @@ public CborMap(ReadOnlyMemory encoding) /// /// A new IDictionary representing this map. /// - public IReadOnlyDictionary AsDictionary() + public IReadOnlyDictionary AsDictionary() { - var returnValue = new Dictionary(_dict.Count); + var returnValue = new Dictionary(_dict.Count); foreach (KeyValuePair entry in _dict) { object? currentValue = ConvertValue(entry.Value); @@ -147,7 +147,7 @@ public IReadOnlyList ReadArray(TKey key) { object? currentValue = ConvertValue(entries[index]); - if (!(currentValue is null) && (currentValue is TValue typedValue)) + if (!(currentValue is null) && currentValue is TValue typedValue) { returnValue.Add(typedValue); continue; @@ -223,8 +223,6 @@ private static int ReadInt32(object? value) { throw new InvalidCastException(null, overflowException); } - - throw new InvalidCastException(); } /// @@ -247,7 +245,6 @@ private static uint ReadUInt32(object? value) throw new InvalidCastException(null, overflowException); } - throw new InvalidCastException(); } /// @@ -265,8 +262,6 @@ private static long ReadInt64(object? value) { throw new InvalidCastException(null, overflowException); } - - throw new InvalidCastException(); } /// @@ -288,8 +283,6 @@ private static ulong ReadUInt64(object? value) { throw new InvalidCastException(null, overflowException); } - - throw new InvalidCastException(); } /// diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/BioEnrollBeginCommand.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/BioEnrollBeginCommand.cs index 6eb84af5..df45ac4e 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/BioEnrollBeginCommand.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/BioEnrollBeginCommand.cs @@ -14,8 +14,8 @@ using System; using Yubico.Core.Iso7816; -using Yubico.YubiKey.Fido2.PinProtocols; using Yubico.YubiKey.Fido2.Cbor; +using Yubico.YubiKey.Fido2.PinProtocols; namespace Yubico.YubiKey.Fido2.Commands { @@ -85,7 +85,7 @@ public BioEnrollBeginResponse CreateResponseForApdu(ResponseApdu responseApdu) = // 03 int private static byte[]? EncodeParams(int? timeoutMilliseconds) { - return (timeoutMilliseconds is null) ? null + return timeoutMilliseconds is null ? null : new CborMapWriter() .Entry(KeyTimeout, timeoutMilliseconds.Value) .Encode(); diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/BioEnrollNextSampleCommand.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/BioEnrollNextSampleCommand.cs index e6a79227..5fa3da02 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/BioEnrollNextSampleCommand.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/BioEnrollNextSampleCommand.cs @@ -14,8 +14,8 @@ using System; using Yubico.Core.Iso7816; -using Yubico.YubiKey.Fido2.PinProtocols; using Yubico.YubiKey.Fido2.Cbor; +using Yubico.YubiKey.Fido2.PinProtocols; namespace Yubico.YubiKey.Fido2.Commands { diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/BioEnrollRemoveCommand.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/BioEnrollRemoveCommand.cs index e2b8db01..6a5c6161 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/BioEnrollRemoveCommand.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/BioEnrollRemoveCommand.cs @@ -14,8 +14,8 @@ using System; using Yubico.Core.Iso7816; -using Yubico.YubiKey.Fido2.PinProtocols; using Yubico.YubiKey.Fido2.Cbor; +using Yubico.YubiKey.Fido2.PinProtocols; namespace Yubico.YubiKey.Fido2.Commands { diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/BioEnrollSetFriendlyNameCommand.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/BioEnrollSetFriendlyNameCommand.cs index 398b8021..fd7cf95f 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/BioEnrollSetFriendlyNameCommand.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/BioEnrollSetFriendlyNameCommand.cs @@ -14,8 +14,8 @@ using System; using Yubico.Core.Iso7816; -using Yubico.YubiKey.Fido2.PinProtocols; using Yubico.YubiKey.Fido2.Cbor; +using Yubico.YubiKey.Fido2.PinProtocols; namespace Yubico.YubiKey.Fido2.Commands { diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/ChangePinCommand.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/ChangePinCommand.cs index 24b63fa2..50d41e5d 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/ChangePinCommand.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/ChangePinCommand.cs @@ -16,8 +16,8 @@ using System.Globalization; using System.Security.Cryptography; using Yubico.Core.Iso7816; -using Yubico.YubiKey.Fido2.PinProtocols; using Yubico.YubiKey.Cryptography; +using Yubico.YubiKey.Fido2.PinProtocols; namespace Yubico.YubiKey.Fido2.Commands { @@ -147,7 +147,7 @@ public ChangePinCommand(PinUvAuthProtocolBase pinProtocol, ReadOnlyMemory CultureInfo.CurrentCulture, ExceptionMessages.InvalidCallOrder)); } - if ((currentPin.Length > MaximumPinLength) || (newPin.Length > MaximumPinLength)) + if (currentPin.Length > MaximumPinLength || newPin.Length > MaximumPinLength) { throw new ArgumentException( string.Format( diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/CredentialManagementData.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/CredentialManagementData.cs index e994fbc1..6df3047c 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/CredentialManagementData.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/CredentialManagementData.cs @@ -136,7 +136,7 @@ public class CredentialManagementData /// Not all calls to get credential management data will return this /// element, hence, it can be null. /// - public CredentialId? CredentialId {get; private set; } + public CredentialId? CredentialId { get; private set; } /// /// The public key for a credential returned. diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/DeleteCredentialCommand.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/DeleteCredentialCommand.cs index 4a73678e..24c81e9d 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/DeleteCredentialCommand.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/DeleteCredentialCommand.cs @@ -14,8 +14,8 @@ using System; using Yubico.Core.Iso7816; -using Yubico.YubiKey.Fido2.PinProtocols; using Yubico.YubiKey.Fido2.Cbor; +using Yubico.YubiKey.Fido2.PinProtocols; namespace Yubico.YubiKey.Fido2.Commands { diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/EnableEnterpriseAttestationCommand.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/EnableEnterpriseAttestationCommand.cs index 7707aa20..30e40da0 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/EnableEnterpriseAttestationCommand.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/EnableEnterpriseAttestationCommand.cs @@ -14,8 +14,8 @@ using System; using Yubico.Core.Iso7816; -using Yubico.YubiKey.Fido2.PinProtocols; using Yubico.YubiKey.Fido2.Cbor; +using Yubico.YubiKey.Fido2.PinProtocols; namespace Yubico.YubiKey.Fido2.Commands { diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/EnumerateCredentialsBeginCommand.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/EnumerateCredentialsBeginCommand.cs index 04f19d84..223fe4d9 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/EnumerateCredentialsBeginCommand.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/EnumerateCredentialsBeginCommand.cs @@ -14,8 +14,8 @@ using System; using Yubico.Core.Iso7816; -using Yubico.YubiKey.Fido2.PinProtocols; using Yubico.YubiKey.Fido2.Cbor; +using Yubico.YubiKey.Fido2.PinProtocols; namespace Yubico.YubiKey.Fido2.Commands { diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/GetFingerprintSensorInfoCommand.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/GetFingerprintSensorInfoCommand.cs index 83e637b9..e1501d7a 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/GetFingerprintSensorInfoCommand.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/GetFingerprintSensorInfoCommand.cs @@ -38,14 +38,14 @@ public sealed class GetFingerprintSensorInfoCommand : IYubiKeyCommand - public CommandApdu CreateCommandApdu() => _command.CreateCommandApdu(); + public CommandApdu CreateCommandApdu() => _command.CreateCommandApdu(); /// - public GetFingerprintSensorInfoResponse CreateResponseForApdu(ResponseApdu responseApdu) => - new GetFingerprintSensorInfoResponse(responseApdu); + public GetFingerprintSensorInfoResponse CreateResponseForApdu(ResponseApdu responseApdu) => + new GetFingerprintSensorInfoResponse(responseApdu); } } diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/GetPinTokenCommand.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/GetPinTokenCommand.cs index 982484d7..7562cdc7 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/GetPinTokenCommand.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/GetPinTokenCommand.cs @@ -13,11 +13,11 @@ // limitations under the License. using System; -using System.Security.Cryptography; using System.Globalization; +using System.Security.Cryptography; +using Yubico.Core.Iso7816; using Yubico.YubiKey.Cryptography; using Yubico.YubiKey.Fido2.PinProtocols; -using Yubico.Core.Iso7816; namespace Yubico.YubiKey.Fido2.Commands { diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/GetPinUvAuthTokenUsingPinCommand.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/GetPinUvAuthTokenUsingPinCommand.cs index 09ef93fc..4db4bc8b 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/GetPinUvAuthTokenUsingPinCommand.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/GetPinUvAuthTokenUsingPinCommand.cs @@ -13,11 +13,11 @@ // limitations under the License. using System; -using System.Security.Cryptography; using System.Globalization; +using System.Security.Cryptography; +using Yubico.Core.Iso7816; using Yubico.YubiKey.Cryptography; using Yubico.YubiKey.Fido2.PinProtocols; -using Yubico.Core.Iso7816; namespace Yubico.YubiKey.Fido2.Commands { diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/GetPinUvAuthTokenUsingUvCommand.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/GetPinUvAuthTokenUsingUvCommand.cs index 3f838f2d..93ac6862 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/GetPinUvAuthTokenUsingUvCommand.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/GetPinUvAuthTokenUsingUvCommand.cs @@ -14,8 +14,8 @@ using System; using System.Globalization; -using Yubico.YubiKey.Fido2.PinProtocols; using Yubico.Core.Iso7816; +using Yubico.YubiKey.Fido2.PinProtocols; namespace Yubico.YubiKey.Fido2.Commands { diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/RequirementValue.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/RequirementValue.cs index dfb50bc7..534b20d7 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/RequirementValue.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/RequirementValue.cs @@ -13,9 +13,9 @@ // limitations under the License. using System; +using System.Collections.Generic; using System.Formats.Cbor; using System.Globalization; -using System.Collections.Generic; using Yubico.YubiKey.Fido2.Cbor; using Yubico.YubiKey.Fido2.Cose; using Yubico.YubiKey.Fido2.PinProtocols; diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/SetLargeBlobCommand.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/SetLargeBlobCommand.cs index d03b2bde..797fd625 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/SetLargeBlobCommand.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/SetLargeBlobCommand.cs @@ -161,7 +161,7 @@ public SetLargeBlobCommand( /// public CommandApdu CreateCommandApdu() { - int count = (_offset == 0) ? CborMapCountInit : CborMapCountUpdate; + int count = _offset == 0 ? CborMapCountInit : CborMapCountUpdate; var cborWriter = new CborWriter(CborConformanceMode.Ctap2Canonical, convertIndefiniteLengthEncodings: true); cborWriter.WriteStartMap(count); cborWriter.WriteInt32(CborKeySet); diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/SetMinPinLengthCommand.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/SetMinPinLengthCommand.cs index 2450bf2d..d8f2eb84 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/SetMinPinLengthCommand.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/SetMinPinLengthCommand.cs @@ -15,8 +15,8 @@ using System; using System.Collections.Generic; using Yubico.Core.Iso7816; -using Yubico.YubiKey.Fido2.PinProtocols; using Yubico.YubiKey.Fido2.Cbor; +using Yubico.YubiKey.Fido2.PinProtocols; namespace Yubico.YubiKey.Fido2.Commands { @@ -202,7 +202,7 @@ public Fido2Response CreateResponseForApdu(ResponseApdu responseApdu) => // 03 bool private static byte[]? EncodeParams(int? minPinLength, IReadOnlyList? rpIds, bool? forceChangePin) { - if ((minPinLength is null) && (rpIds is null) && (forceChangePin is null)) + if (minPinLength is null && rpIds is null && forceChangePin is null) { return null; } diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/ToggleAlwaysUvCommand.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/ToggleAlwaysUvCommand.cs index 2507cf14..9c5acb6f 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/ToggleAlwaysUvCommand.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/ToggleAlwaysUvCommand.cs @@ -14,8 +14,8 @@ using System; using Yubico.Core.Iso7816; -using Yubico.YubiKey.Fido2.PinProtocols; using Yubico.YubiKey.Fido2.Cbor; +using Yubico.YubiKey.Fido2.PinProtocols; namespace Yubico.YubiKey.Fido2.Commands { diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/UpdateUserInfoCommand.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/UpdateUserInfoCommand.cs index 5bf4f9c4..7101ed74 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/UpdateUserInfoCommand.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/UpdateUserInfoCommand.cs @@ -14,8 +14,8 @@ using System; using Yubico.Core.Iso7816; -using Yubico.YubiKey.Fido2.PinProtocols; using Yubico.YubiKey.Fido2.Cbor; +using Yubico.YubiKey.Fido2.PinProtocols; namespace Yubico.YubiKey.Fido2.Commands { diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Cose/CoseEcPublicKey.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Cose/CoseEcPublicKey.cs index bf9d479c..7a8d3fbc 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Cose/CoseEcPublicKey.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Cose/CoseEcPublicKey.cs @@ -157,8 +157,8 @@ private CoseEcPublicKey() /// public CoseEcPublicKey(CoseEcCurve curve, ReadOnlyMemory xCoordinate, ReadOnlyMemory yCoordinate) { - if ((curve != CoseEcCurve.P256) || (xCoordinate.Length == 0) || (xCoordinate.Length > P256CoordinateLength) - || (yCoordinate.Length == 0) || (yCoordinate.Length > P256CoordinateLength)) + if (curve != CoseEcCurve.P256 || xCoordinate.Length == 0 || xCoordinate.Length > P256CoordinateLength + || yCoordinate.Length == 0 || yCoordinate.Length > P256CoordinateLength) { throw new ArgumentException(ExceptionMessages.InvalidPublicKeyData); } @@ -248,7 +248,7 @@ public ECParameters ToEcParameters() /// public override byte[] Encode() { - if ((_xCoordinate.Length != P256CoordinateLength) || (_yCoordinate.Length != P256CoordinateLength)) + if (_xCoordinate.Length != P256CoordinateLength || _yCoordinate.Length != P256CoordinateLength) { throw new InvalidOperationException( string.Format( diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Cose/CoseKey.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Cose/CoseKey.cs index 820959be..82a7e7df 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Cose/CoseKey.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Cose/CoseKey.cs @@ -13,8 +13,8 @@ // limitations under the License. using System; -using System.Globalization; using System.Formats.Cbor; +using System.Globalization; using Yubico.YubiKey.Fido2.Cbor; namespace Yubico.YubiKey.Fido2.Cose @@ -119,7 +119,7 @@ public static CoseKey Create(ReadOnlyMemory coseEncodedKey, out int bytesR // (ECDHwHKDF256). If the -25 seems odd, it is specified in the FIDO2 // standard. var algorithm = (CoseAlgorithmIdentifier)map.ReadInt32(TagAlgorithm); - if ((algorithm == CoseAlgorithmIdentifier.ECDHwHKDF256) || (algorithm == CoseAlgorithmIdentifier.ES256)) + if (algorithm == CoseAlgorithmIdentifier.ECDHwHKDF256 || algorithm == CoseAlgorithmIdentifier.ES256) { return new CoseEcPublicKey(coseEncodedKey); } diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/CredentialId.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/CredentialId.cs index 151d9725..01a6f466 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/CredentialId.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/CredentialId.cs @@ -13,9 +13,9 @@ // limitations under the License. using System; +using System.Collections.Generic; using System.Formats.Cbor; using System.Globalization; -using System.Collections.Generic; using Yubico.YubiKey.Fido2.Cbor; namespace Yubico.YubiKey.Fido2 @@ -201,7 +201,7 @@ public void AddTransport(string transport) { _transports.Add(transport); } - } + } /// public byte[] CborEncode() diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/CredentialUserInfo.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/CredentialUserInfo.cs index 1c3b3979..a6761f48 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/CredentialUserInfo.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/CredentialUserInfo.cs @@ -32,7 +32,7 @@ public class CredentialUserInfo /// /// The credential ID for a credential returned. /// - public CredentialId CredentialId {get; private set; } + public CredentialId CredentialId { get; private set; } /// /// The public key for a credential returned. diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Fido2Session.BioEnrollment.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Fido2Session.BioEnrollment.cs index 5d54d892..01bbfff8 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Fido2Session.BioEnrollment.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Fido2Session.BioEnrollment.cs @@ -13,10 +13,10 @@ // limitations under the License. using System; -using System.Threading; -using System.Threading.Tasks; using System.Collections.Generic; using System.Security; +using System.Threading; +using System.Threading.Tasks; using Yubico.Core.Logging; using Yubico.YubiKey.Fido2.Commands; @@ -47,7 +47,7 @@ public BioModality GetBioModality() var cmd = new GetBioModalityCommand(); GetBioModalityResponse rsp = Connection.SendCommand(cmd); - int modality = (rsp.Status == ResponseStatus.Success) ? rsp.GetData() : 0; + int modality = rsp.Status == ResponseStatus.Success ? rsp.GetData() : 0; return modality switch { @@ -79,7 +79,7 @@ public FingerprintSensorInfo GetFingerprintSensorInfo() var cmd = new GetFingerprintSensorInfoCommand(); GetFingerprintSensorInfoResponse rsp = Connection.SendCommand(cmd); - return (rsp.Status == ResponseStatus.Success) ? + return rsp.Status == ResponseStatus.Success ? rsp.GetData() : throw new NotSupportedException(ExceptionMessages.NotSupportedByYubiKeyVersion); } @@ -265,7 +265,7 @@ public TemplateInfo EnrollFingerprint(string? friendlyName, int? timeoutMillisec if (!string.IsNullOrEmpty(friendlyName)) { returnName = friendlyName!; - foreach(TemplateInfo templateInfo in templateList) + foreach (TemplateInfo templateInfo in templateList) { if (returnName!.Equals(templateInfo.FriendlyName, StringComparison.Ordinal)) { @@ -320,7 +320,7 @@ public TemplateInfo EnrollFingerprint(string? friendlyName, int? timeoutMillisec generalErrorMsg = nextRsp.StatusMessage; } - if ((status == CtapStatus.Ok) && !string.IsNullOrEmpty(returnName)) + if (status == CtapStatus.Ok && !string.IsNullOrEmpty(returnName)) { var nameCmd = new BioEnrollSetFriendlyNameCommand(templateId, returnName, currentToken, AuthProtocol); Fido2Response nameRsp = Connection.SendCommand(nameCmd); @@ -432,7 +432,7 @@ public bool TryRemoveBioTemplate(ReadOnlyMemory templateId) removeRsp = Connection.SendCommand(removeCmd); } - return (removeRsp.Status == ResponseStatus.Success) || (removeRsp.CtapStatus == CtapStatus.InvalidOption); + return removeRsp.Status == ResponseStatus.Success || removeRsp.CtapStatus == CtapStatus.InvalidOption; } } } diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Fido2Session.Config.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Fido2Session.Config.cs index a510ada5..1d3faf4a 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Fido2Session.Config.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Fido2Session.Config.cs @@ -165,7 +165,7 @@ public bool TryToggleAlwaysUv() _log.LogInformation("Try to ToggleAlwaysUv."); OptionValue alwaysUvValue = AuthenticatorInfo.GetOptionValue(AuthenticatorOptions.alwaysUv); - if ((alwaysUvValue != OptionValue.True) && (alwaysUvValue != OptionValue.False)) + if (alwaysUvValue != OptionValue.True && alwaysUvValue != OptionValue.False) { return false; } diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Fido2Session.CredMgmt.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Fido2Session.CredMgmt.cs index 7a1ef37a..2e38ebfa 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Fido2Session.CredMgmt.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Fido2Session.CredMgmt.cs @@ -13,9 +13,9 @@ // limitations under the License. using System; -using System.Text; using System.Collections.Generic; using System.Security.Cryptography; +using System.Text; using Yubico.Core.Logging; using Yubico.YubiKey.Cryptography; using Yubico.YubiKey.Fido2.Commands; @@ -442,7 +442,7 @@ public void DeleteCredential(CredentialId credentialId) } // If the response is Success, we're done. - if ((rsp.Status == ResponseStatus.Success) || (rsp.CtapStatus == CtapStatus.NoCredentials)) + if (rsp.Status == ResponseStatus.Success || rsp.CtapStatus == CtapStatus.NoCredentials) { // After a credential has been deleted, the number of // discoverable credentials can change. Hence, this operation can diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Fido2Session.GetAssertion.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Fido2Session.GetAssertion.cs index 180b338b..623fcb44 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Fido2Session.GetAssertion.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Fido2Session.GetAssertion.cs @@ -15,8 +15,8 @@ using System; using System.Collections.Generic; using System.Security.Cryptography; -using Yubico.YubiKey.Fido2.Commands; using Yubico.Core.Logging; +using Yubico.YubiKey.Fido2.Commands; namespace Yubico.YubiKey.Fido2 { diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Fido2Session.LargeBlobs.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Fido2Session.LargeBlobs.cs index abc74e14..df99a5e0 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Fido2Session.LargeBlobs.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Fido2Session.LargeBlobs.cs @@ -13,13 +13,13 @@ // limitations under the License. using System; -using System.IO; using System.Buffers.Binary; +using System.IO; using System.Security.Cryptography; using Yubico.Core.Logging; using Yubico.YubiKey.Cryptography; -using Yubico.YubiKey.Fido2.Commands; using Yubico.YubiKey.Fido2.Cbor; +using Yubico.YubiKey.Fido2.Commands; namespace Yubico.YubiKey.Fido2 { @@ -118,7 +118,7 @@ public SerializedLargeBlobArray GetSerializedLargeBlobArray() int maxFragmentLength = AuthenticatorInfo.MaximumMessageSize ?? AuthenticatorInfo.DefaultMaximumMessageSize; using var fullEncoding = new MemoryStream(maxFragmentLength); - maxFragmentLength -= MessageOverhead; + maxFragmentLength -= MessageOverhead; ReadOnlyMemory currentData; @@ -234,7 +234,7 @@ public void SetSerializedLargeBlobArray(SerializedLargeBlobArray serializedLarge int offset = 0; int remaining = encodedArray.Length; int maxFragmentLength = AuthenticatorInfo.MaximumMessageSize ?? AuthenticatorInfo.DefaultMaximumMessageSize; - maxFragmentLength -= MessageOverhead; + maxFragmentLength -= MessageOverhead; int currentLength; bool forceToken = false; @@ -246,7 +246,7 @@ public void SetSerializedLargeBlobArray(SerializedLargeBlobArray serializedLarge forceToken, PinUvAuthTokenPermissions.LargeBlobWrite, null); currentToken.CopyTo(token.AsMemory()); - currentLength = (remaining >= maxFragmentLength) ? maxFragmentLength : remaining; + currentLength = remaining >= maxFragmentLength ? maxFragmentLength : remaining; byte[] dataToAuth = BuildDataToAuth(encodedArray, offset, currentLength, digester); byte[] pinUvAuthParam = AuthProtocol.AuthenticateUsingPinToken(token, 0, currentToken.Length, dataToAuth); @@ -264,7 +264,7 @@ public void SetSerializedLargeBlobArray(SerializedLargeBlobArray serializedLarge offset += currentLength; forceToken = false; } - else if ((response.CtapStatus == CtapStatus.PinAuthInvalid) && !forceToken) + else if (response.CtapStatus == CtapStatus.PinAuthInvalid && !forceToken) { forceToken = true; } diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Fido2Session.MakeCredential.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Fido2Session.MakeCredential.cs index 42f89fef..d568f345 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Fido2Session.MakeCredential.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Fido2Session.MakeCredential.cs @@ -14,8 +14,8 @@ using System; using System.Security.Cryptography; -using Yubico.YubiKey.Fido2.Commands; using Yubico.Core.Logging; +using Yubico.YubiKey.Fido2.Commands; namespace Yubico.YubiKey.Fido2 { diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Fido2Session.Pin.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Fido2Session.Pin.cs index c723e142..917870cd 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Fido2Session.Pin.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Fido2Session.Pin.cs @@ -15,10 +15,10 @@ using System; using System.Globalization; using System.Security; +using Yubico.Core.Logging; using Yubico.YubiKey.Fido2.Commands; using Yubico.YubiKey.Fido2.Cose; using Yubico.YubiKey.Fido2.PinProtocols; -using Yubico.Core.Logging; namespace Yubico.YubiKey.Fido2 { @@ -314,7 +314,7 @@ public void AddPermissions(PinUvAuthTokenPermissions permissions, string? relyin // If the permissions requested require an RpId, then make sure there // is one. - if ((allPermissions.GetRpIdRequirement() == RequirementValue.Required) && (rpId is null)) + if (allPermissions.GetRpIdRequirement() == RequirementValue.Required && rpId is null) { throw new InvalidOperationException(ExceptionMessages.Fido2RelyingPartyMissing); } @@ -1008,7 +1008,7 @@ public bool TryVerifyPin( ObtainSharedSecret(); - if (!permissions.HasValue || (permissions == PinUvAuthTokenPermissions.None)) + if (!permissions.HasValue || permissions == PinUvAuthTokenPermissions.None) { if (!string.IsNullOrEmpty(relyingPartyId)) { @@ -1188,7 +1188,7 @@ public bool TryVerifyUv(PinUvAuthTokenPermissions permissions, string? relyingPa _log.LogInformation("Try to verify UV (use KeyCollector)."); CtapStatus status = DoVerifyUv(permissions, relyingPartyId, out string statusMessage); - switch(status) + switch (status) { case CtapStatus.Ok: return true; @@ -1215,8 +1215,8 @@ public bool TryVerifyUv(PinUvAuthTokenPermissions permissions, string? relyingPa private CtapStatus DoVerifyUv(PinUvAuthTokenPermissions permissions, string? relyingPartyId, out string statusMessage) { - if ((AuthenticatorInfo.GetOptionValue("pinUvAuthToken") != OptionValue.True) - || (AuthenticatorInfo.GetOptionValue("uv") != OptionValue.True)) + if (AuthenticatorInfo.GetOptionValue("pinUvAuthToken") != OptionValue.True + || AuthenticatorInfo.GetOptionValue("uv") != OptionValue.True) { statusMessage = ""; return CtapStatus.UnsupportedOption; @@ -1266,7 +1266,7 @@ private CtapStatus DoVerifyUv(PinUvAuthTokenPermissions permissions, string? rel status = CtapStatus.LimitExceeded; } } - } while(status == CtapStatus.UvInvalid); + } while (status == CtapStatus.UvInvalid); return status; } diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/GetAssertionData.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/GetAssertionData.cs index 8833d5e0..601fe00d 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/GetAssertionData.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/GetAssertionData.cs @@ -13,9 +13,9 @@ // limitations under the License. using System; +using System.Collections.Generic; using System.Formats.Cbor; using System.Globalization; -using System.Collections.Generic; using System.Security.Cryptography; using Yubico.YubiKey.Cryptography; using Yubico.YubiKey.Fido2.Cbor; @@ -48,7 +48,6 @@ public class GetAssertionData : IDisposable private const string KeyUserName = "name"; private const string KeyUserDisplayName = "displayName"; -// private readonly Logger _log = Log.GetLogger(); private bool _disposed; private readonly byte[]? _keyData; diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/GetAssertionParameters.Extensions.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/GetAssertionParameters.Extensions.cs index 2b716191..9014d1d0 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/GetAssertionParameters.Extensions.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/GetAssertionParameters.Extensions.cs @@ -208,7 +208,7 @@ public void RequestHmacSecretExtension( if (salt1.Length == HmacSecretSaltLength) { - int s2Len = (salt2 is null) ? HmacSecretSaltLength : salt2.Value.Length; + int s2Len = salt2 is null ? HmacSecretSaltLength : salt2.Value.Length; _salt1 = salt1; if (s2Len == HmacSecretSaltLength) { @@ -286,7 +286,7 @@ public void EncodeHmacSecretExtension(PinUvAuthProtocolBase authProtocol) { throw new ArgumentNullException(nameof(authProtocol)); } - if ((authProtocol.EncryptionKey is null) || (authProtocol.PlatformPublicKey is null)) + if (authProtocol.EncryptionKey is null || authProtocol.PlatformPublicKey is null) { throw new InvalidOperationException(ExceptionMessages.Fido2NotEncapsulated); } @@ -319,5 +319,5 @@ public void EncodeHmacSecretExtension(PinUvAuthProtocolBase authProtocol) .Entry(TagPinProtocol, (int)authProtocol.Protocol) .Encode(); } - } + } } diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/GetAssertionParameters.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/GetAssertionParameters.cs index 3fe89dd0..4b0db309 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/GetAssertionParameters.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/GetAssertionParameters.cs @@ -272,5 +272,5 @@ public byte[] CborEncode() .OptionalEntry(TagProtocol, (int?)Protocol) .Encode(); } - } + } } diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/LargeBlobEntry.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/LargeBlobEntry.cs index 0e155e8c..f449ebf2 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/LargeBlobEntry.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/LargeBlobEntry.cs @@ -13,10 +13,10 @@ // limitations under the License. using System; -using System.IO; -using System.IO.Compression; using System.Buffers.Binary; using System.Formats.Cbor; +using System.IO; +using System.IO.Compression; using System.Security.Cryptography; using Yubico.Core.Cryptography; using Yubico.Core.Logging; @@ -176,7 +176,7 @@ internal LargeBlobEntry(ReadOnlyMemory cborEncoding) // Make sure the data includes the tag plus at least one byte, // and that there is original data. - if ((OriginalDataLength > 0) && (Ciphertext.Length > GcmTagSize)) + if (OriginalDataLength > 0 && Ciphertext.Length > GcmTagSize) { return; } diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/MakeCredentialData.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/MakeCredentialData.cs index 2ddcc476..3ebd7f9c 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/MakeCredentialData.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/MakeCredentialData.cs @@ -13,11 +13,11 @@ // limitations under the License. using System; +using System.Collections.Generic; using System.Formats.Cbor; -using System.Security.Cryptography; using System.Globalization; +using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; -using System.Collections.Generic; using Yubico.YubiKey.Cryptography; using Yubico.YubiKey.Fido2.Cbor; using Yubico.YubiKey.Fido2.Cose; @@ -200,7 +200,7 @@ public MakeCredentialData(ReadOnlyMemory cborEncoding) Format = map.ReadTextString(KeyFormat); AuthenticatorData = new AuthenticatorData(map.ReadByteString(KeyAuthData)); if (!(AuthenticatorData.CredentialPublicKey is CoseEcPublicKey) - || (AuthenticatorData.CredentialPublicKey.Type != CoseKeyType.Ec2) + || AuthenticatorData.CredentialPublicKey.Type != CoseKeyType.Ec2 || !map.Contains(KeyAttestationStatement) || !ReadAttestation(map)) { @@ -240,8 +240,8 @@ private bool ReadAttestation(CborMap map) EncodedAttestationStatement = attest.Encoded; if (!Format.Equals(PackedString, StringComparison.Ordinal) || !attest.Contains(AlgString) || !attest.Contains(SigString) - || (attest.Count > MaxAttestationMapCount) - || ((attest.Count == MaxAttestationMapCount) && !attest.Contains(X5cString))) + || attest.Count > MaxAttestationMapCount + || (attest.Count == MaxAttestationMapCount && !attest.Contains(X5cString))) { return false; } @@ -288,7 +288,7 @@ private bool ReadAttestation(CborMap map) /// public bool VerifyAttestation(ReadOnlyMemory clientDataHash) { - if ((AttestationCertificates is null) || (AttestationCertificates.Count == 0)) + if (AttestationCertificates is null || AttestationCertificates.Count == 0) { throw new InvalidOperationException(ExceptionMessages.MissingCtap2Data); } diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/MakeCredentialParameters.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/MakeCredentialParameters.cs index c25f42c1..1cb1e3f7 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/MakeCredentialParameters.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/MakeCredentialParameters.cs @@ -13,10 +13,10 @@ // limitations under the License. using System; -using System.Formats.Cbor; using System.Collections.Generic; -using System.Linq; +using System.Formats.Cbor; using System.Globalization; +using System.Linq; using Yubico.YubiKey.Fido2.Cbor; using Yubico.YubiKey.Fido2.Cose; using Yubico.YubiKey.Fido2.PinProtocols; @@ -695,8 +695,8 @@ public byte[] CborEncode() .Entry(TagUserEntity, UserEntity) .Entry(TagAlgorithmsList, EncodeAlgorithms, this) .OptionalEntry>(TagExcludeList, CborHelpers.EncodeArrayOfObjects, ExcludeList) - .OptionalEntry>(TagExtensions, ParameterHelpers.EncodeKeyValues, _extensions) - .OptionalEntry>(TagOptions, ParameterHelpers.EncodeKeyValues, _options) + .OptionalEntry>(TagExtensions, ParameterHelpers.EncodeKeyValues, _extensions) + .OptionalEntry>(TagOptions, ParameterHelpers.EncodeKeyValues, _options) .OptionalEntry(TagPinUvAuth, PinUvAuthParam) .OptionalEntry(TagProtocol, (int?)Protocol) .OptionalEntry(TagEnterpriseAttestation, (int?)EnterpriseAttestation) @@ -705,7 +705,7 @@ public byte[] CborEncode() private byte[] EncodeAlgorithms(MakeCredentialParameters? localData) { - if ((localData is null) || (localData.Algorithms.Count == 0)) + if (localData is null || localData.Algorithms.Count == 0) { return Array.Empty(); } diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/OptionValue.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/OptionValue.cs index af698c7f..961e32c1 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/OptionValue.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/OptionValue.cs @@ -13,9 +13,9 @@ // limitations under the License. using System; +using System.Collections.Generic; using System.Formats.Cbor; using System.Globalization; -using System.Collections.Generic; using Yubico.YubiKey.Fido2.Cbor; using Yubico.YubiKey.Fido2.Cose; using Yubico.YubiKey.Fido2.PinProtocols; diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/ParameterHelpers.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/ParameterHelpers.cs index 5d453e56..9e9382ac 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/ParameterHelpers.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/ParameterHelpers.cs @@ -13,9 +13,9 @@ // limitations under the License. using System; -using System.Globalization; using System.Collections.Generic; using System.Formats.Cbor; +using System.Globalization; using Yubico.YubiKey.Fido2.Cose; namespace Yubico.YubiKey.Fido2 @@ -44,7 +44,7 @@ public static List AddToList(T itemToAdd, List? currentList) throw new ArgumentNullException(); } - List returnList = (currentList is null) ? new List() : currentList; + List returnList = currentList is null ? new List() : currentList; returnList.Add(itemToAdd); return returnList; @@ -71,7 +71,7 @@ public static Dictionary AddKeyValue( } Dictionary returnDictionary = - (currentDictionary is null) ? new Dictionary() : currentDictionary; + currentDictionary is null ? new Dictionary() : currentDictionary; // If the key already exists, replace the current value in the // dictionary with this one. @@ -103,9 +103,9 @@ public static Dictionary AddKeyValue( /// (localData is null or a the Count is zero), the /// return will be an empty byte array. /// - public static byte[] EncodeKeyValues(IReadOnlyDictionary? localData) + public static byte[] EncodeKeyValues(IReadOnlyDictionary? localData) { - if ((localData is null) || (localData.Count == 0)) + if (localData is null || localData.Count == 0) { return Array.Empty(); } diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/PinProtocols/PinUvAuthProtocolOne.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/PinProtocols/PinUvAuthProtocolOne.cs index 52697b9e..74d945ca 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/PinProtocols/PinUvAuthProtocolOne.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/PinProtocols/PinUvAuthProtocolOne.cs @@ -56,7 +56,7 @@ public override byte[] Encrypt(byte[] plaintext, int offset, int length) { throw new ArgumentNullException(nameof(plaintext)); } - if ((length < BlockSize) || ((length % BlockSize) != 0) || ((offset + length) > plaintext.Length)) + if (length < BlockSize || length % BlockSize != 0 || offset + length > plaintext.Length) { throw new ArgumentException( string.Format( @@ -92,7 +92,7 @@ public override byte[] Decrypt(byte[] ciphertext, int offset, int length) { throw new ArgumentNullException(nameof(ciphertext)); } - if ((length == 0) || (length % BlockSize != 0) || (offset + length > ciphertext.Length)) + if (length == 0 || length % BlockSize != 0 || offset + length > ciphertext.Length) { throw new ArgumentException( string.Format( diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/PinProtocols/PinUvAuthProtocolTwo.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/PinProtocols/PinUvAuthProtocolTwo.cs index b3c5cde5..f69c5e76 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/PinProtocols/PinUvAuthProtocolTwo.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/PinProtocols/PinUvAuthProtocolTwo.cs @@ -15,8 +15,8 @@ using System; using System.Globalization; using System.IO; -using System.Text; using System.Security.Cryptography; +using System.Text; using Yubico.YubiKey.Cryptography; namespace Yubico.YubiKey.Fido2.PinProtocols @@ -63,7 +63,7 @@ public override byte[] Encrypt(byte[] plaintext, int offset, int length) { throw new ArgumentNullException(nameof(plaintext)); } - if ((length == 0) || ((length % BlockSize) != 0) || ((offset + length) > plaintext.Length)) + if (length == 0 || length % BlockSize != 0 || offset + length > plaintext.Length) { throw new ArgumentException( string.Format( @@ -109,7 +109,7 @@ public override byte[] Decrypt(byte[] ciphertext, int offset, int length) } // The first BlockSize bytes are the IV, so there should be at least // 2 blocks. - if ((length < 2 * BlockSize) || ((length % BlockSize) != 0) || ((offset + length) > ciphertext.Length)) + if (length < 2 * BlockSize || length % BlockSize != 0 || offset + length > ciphertext.Length) { throw new ArgumentException( string.Format( diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/RelyingParty.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/RelyingParty.cs index 15a765b8..a143dbce 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/RelyingParty.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/RelyingParty.cs @@ -13,12 +13,12 @@ // limitations under the License. using System; -using System.Text; using System.Formats.Cbor; using System.Globalization; using System.Security.Cryptography; -using Yubico.YubiKey.Fido2.Cbor; +using System.Text; using Yubico.YubiKey.Cryptography; +using Yubico.YubiKey.Fido2.Cbor; namespace Yubico.YubiKey.Fido2 { diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/SerializedLargeBlobArray.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/SerializedLargeBlobArray.cs index 2eb09c06..df5998c2 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/SerializedLargeBlobArray.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/SerializedLargeBlobArray.cs @@ -13,9 +13,9 @@ // limitations under the License. using System; +using System.Collections.Generic; using System.Formats.Cbor; using System.Globalization; -using System.Collections.Generic; using System.Security.Cryptography; using Yubico.Core.Logging; using Yubico.YubiKey.Cryptography; diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/UserEntity.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/UserEntity.cs index 7eebb87d..3e4c39f1 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/UserEntity.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/UserEntity.cs @@ -13,9 +13,9 @@ // limitations under the License. using System; +using System.Collections.Generic; using System.Formats.Cbor; using System.Globalization; -using System.Collections.Generic; using Yubico.YubiKey.Fido2.Cbor; namespace Yubico.YubiKey.Fido2 diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/FidoConnection.cs b/Yubico.YubiKey/src/Yubico/YubiKey/FidoConnection.cs index acfc7ae3..ccf36a64 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/FidoConnection.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/FidoConnection.cs @@ -12,9 +12,9 @@ // See the License for the specific language governing permissions and // limitations under the License. -using Yubico.YubiKey.Pipelines; using Yubico.Core.Devices.Hid; using Yubico.Core.Iso7816; +using Yubico.YubiKey.Pipelines; namespace Yubico.YubiKey { diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/FidoDeviceInfoFactory.cs b/Yubico.YubiKey/src/Yubico/YubiKey/FidoDeviceInfoFactory.cs index 53304571..3240c602 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/FidoDeviceInfoFactory.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/FidoDeviceInfoFactory.cs @@ -12,13 +12,13 @@ // See the License for the specific language governing permissions and // limitations under the License. -using Yubico.Core.Devices.Hid; -using Yubico.YubiKey.DeviceExtensions; -using System.Diagnostics; using System; +using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using Microsoft.Extensions.Logging; +using Yubico.Core.Devices.Hid; using Yubico.Core.Logging; +using Yubico.YubiKey.DeviceExtensions; namespace Yubico.YubiKey { diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/FirmwareVersion.cs b/Yubico.YubiKey/src/Yubico/YubiKey/FirmwareVersion.cs index e1677b3b..2ce17a4f 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/FirmwareVersion.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/FirmwareVersion.cs @@ -174,7 +174,7 @@ public int CompareTo(FirmwareVersion other) { return 0; } - else if (other is null) + if (other is null) { return 1; } @@ -190,15 +190,11 @@ public int CompareTo(FirmwareVersion other) int patchComparison = Patch.CompareTo(other.Patch); return patchComparison; } - else - { - return minorComparison; - } - } - else - { - return majorComparison; + + return minorComparison; } + + return majorComparison; } } } diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/KeyboardDeviceInfoFactory.cs b/Yubico.YubiKey/src/Yubico/YubiKey/KeyboardDeviceInfoFactory.cs index 13a6fd5a..097f8d1b 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/KeyboardDeviceInfoFactory.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/KeyboardDeviceInfoFactory.cs @@ -12,11 +12,11 @@ // See the License for the specific language governing permissions and // limitations under the License. -using Yubico.Core.Devices.Hid; -using Yubico.YubiKey.DeviceExtensions; using System; using System.Diagnostics.CodeAnalysis; +using Yubico.Core.Devices.Hid; using Yubico.Core.Logging; +using Yubico.YubiKey.DeviceExtensions; namespace Yubico.YubiKey { diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/KeyboardReport.cs b/Yubico.YubiKey/src/Yubico/YubiKey/KeyboardReport.cs index 21fe9974..ef7992dd 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/KeyboardReport.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/KeyboardReport.cs @@ -98,11 +98,11 @@ public KeyboardReport(Memory reportBuffer) public override string ToString() { return - $"TouchPending: { TouchPending }, " + - $"ReadPending: { ReadPending }, " + - $"WritePending: { WritePending }, " + - $"SequenceNumber: { SequenceNumber }, " + - $"Payload: { BitConverter.ToString(PayloadSpan().ToArray()) }"; + $"TouchPending: {TouchPending}, " + + $"ReadPending: {ReadPending}, " + + $"WritePending: {WritePending}, " + + $"SequenceNumber: {SequenceNumber}, " + + $"Payload: {BitConverter.ToString(PayloadSpan().ToArray())}"; } } } diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Management/Commands/SetDeviceInfoBaseCommand.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Management/Commands/SetDeviceInfoBaseCommand.cs index c680c7d5..2403bf68 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Management/Commands/SetDeviceInfoBaseCommand.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Management/Commands/SetDeviceInfoBaseCommand.cs @@ -79,7 +79,7 @@ public int? AutoEjectTimeout { if (value.HasValue) { - if ((value < ushort.MinValue) || (value > ushort.MaxValue)) + if (value < ushort.MinValue || value > ushort.MaxValue) { throw new ArgumentOutOfRangeException(nameof(value)); } diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Management/Commands/SetLegacyDeviceConfigBase.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Management/Commands/SetLegacyDeviceConfigBase.cs index 6f76cd20..755da34a 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Management/Commands/SetLegacyDeviceConfigBase.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Management/Commands/SetLegacyDeviceConfigBase.cs @@ -74,7 +74,7 @@ public static bool ContainsOnlyValidInterfaceFlags(YubiKeyCapabilities yubiKeyIn public YubiKeyCapabilities YubiKeyInterfaces { get => _yubiKeyInterfaces; - + set { if (!ContainsOnlyValidInterfaceFlags(value)) @@ -112,7 +112,7 @@ public int AutoEjectTimeout set { - if ((value < ushort.MinValue) || (value > ushort.MaxValue)) + if (value < ushort.MinValue || value > ushort.MaxValue) { throw new ArgumentOutOfRangeException(nameof(value)); } diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Code.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Code.cs index b5420a0a..d43ef489 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Code.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Code.cs @@ -75,7 +75,8 @@ public Code(string? value, CredentialPeriod period) throw new ArgumentException(ExceptionMessages.InvalidCredentialPeriod); } - if (!string.IsNullOrWhiteSpace(value)) { + if (!string.IsNullOrWhiteSpace(value)) + { Value = value; DateTimeOffset timestamp = DateTimeOffset.UtcNow; diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Commands/CalculateAllCredentialsCommand.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Commands/CalculateAllCredentialsCommand.cs index 900b13f5..af5e458b 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Commands/CalculateAllCredentialsCommand.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Commands/CalculateAllCredentialsCommand.cs @@ -25,7 +25,7 @@ public class CalculateAllCredentialsCommand : OathChallengeResponseBaseCommand, { private const byte CalculateAllInstruction = 0xA4; private const byte ChallengeTag = 0x74; - + /// /// Full or truncated response to receive back. /// @@ -65,7 +65,7 @@ public CalculateAllCredentialsCommand(ResponseFormat responseFormat) public CommandApdu CreateCommandApdu() { var tlvWriter = new TlvWriter(); - + // Using default period which is 30 seconds for calculating all credentials. // Credentials that have different period are recalculated later in CalculateAllCredentialsResponse. tlvWriter.WriteValue(ChallengeTag, GenerateTotpChallenge(CredentialPeriod.Period30)); diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Commands/CalculateCredentialCommand.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Commands/CalculateCredentialCommand.cs index 7539f162..cf61c015 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Commands/CalculateCredentialCommand.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Commands/CalculateCredentialCommand.cs @@ -92,7 +92,7 @@ public CommandApdu CreateCommandApdu() { throw new InvalidOperationException(ExceptionMessages.InvalidCredentialType); } - + if (Credential.Period is null) { throw new InvalidOperationException(ExceptionMessages.InvalidCredentialPeriod); diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Commands/ListCommand.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Commands/ListCommand.cs index 1dfda351..c291b3a8 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Commands/ListCommand.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Commands/ListCommand.cs @@ -25,7 +25,7 @@ namespace Yubico.YubiKey.Oath.Commands public class ListCommand : IYubiKeyCommand { private const byte ListInstruction = 0xa1; - + /// /// Gets the YubiKeyApplication to which this command belongs. /// diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Commands/OathChallengeResponseBaseCommand.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Commands/OathChallengeResponseBaseCommand.cs index fc055fa7..27d67609 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Commands/OathChallengeResponseBaseCommand.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Commands/OathChallengeResponseBaseCommand.cs @@ -34,10 +34,7 @@ public abstract class OathChallengeResponseBaseCommand /// protected static byte[] GenerateTotpChallenge(CredentialPeriod? period) { - if (period is null) - { - period = CredentialPeriod.Period30; - } + period ??= CredentialPeriod.Period30; ulong timePeriod = (uint)DateTimeOffset.UtcNow.ToUnixTimeSeconds() / (uint)period; byte[] bytes = new byte[8]; @@ -61,7 +58,7 @@ protected static byte[] GenerateRandomChallenge() byte[] randomBytes = new byte[8]; randomObject.GetBytes(randomBytes); - + return randomBytes; } diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Commands/OathResponse.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Commands/OathResponse.cs index 6bdf1406..f9cb88bd 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Commands/OathResponse.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Commands/OathResponse.cs @@ -21,7 +21,7 @@ namespace Yubico.YubiKey.Oath.Commands /// or one of its derived classes to retrieve the full response. /// /// - public class OathResponse: YubiKeyResponse + public class OathResponse : YubiKeyResponse { public OathResponse(ResponseApdu responseApdu) : base(responseApdu) diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Commands/RenameCommand.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Commands/RenameCommand.cs index 708334c9..87380a49 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Commands/RenameCommand.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Commands/RenameCommand.cs @@ -113,7 +113,7 @@ public CommandApdu CreateCommandApdu() var newCredential = new Credential { - Issuer = NewIssuer, + Issuer = NewIssuer, AccountName = NewAccount, Type = Credential.Type, Period = Credential.Period diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Commands/ValidateCommand.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Commands/ValidateCommand.cs index d2ca7c86..9a99d6ea 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Commands/ValidateCommand.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Commands/ValidateCommand.cs @@ -96,9 +96,9 @@ public CommandApdu CreateCommandApdu() return new CommandApdu { - Ins = ValidateInstruction, + Ins = ValidateInstruction, Data = tlvWriter.Encode() - }; + }; } /// diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Commands/ValidateResponse.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Commands/ValidateResponse.cs index a2776ec6..5d98a025 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Commands/ValidateResponse.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Commands/ValidateResponse.cs @@ -24,7 +24,7 @@ namespace Yubico.YubiKey.Oath.Commands public class ValidateResponse : OathResponse, IYubiKeyResponseWithData { private const byte ResponseTag = 0x75; - + /// protected override ResponseStatusPair StatusCodeMap => StatusWord switch diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Credential.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Credential.cs index 998248fe..b6823137 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Credential.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Credential.cs @@ -15,11 +15,11 @@ using System; using System.Collections.Specialized; using System.Diagnostics.CodeAnalysis; -using System.Web; using System.Globalization; using System.Linq; using System.Text; using System.Text.RegularExpressions; +using System.Web; using static System.Convert; namespace Yubico.YubiKey.Oath @@ -94,7 +94,7 @@ public HashAlgorithm? Algorithm } _algorithm = value; - } + } } /// @@ -146,7 +146,8 @@ public string? Secret get => _secret; set { - if (value != null) { + if (value != null) + { var regexSecret = new Regex(@"[A-Za-z2-7=]*"); @@ -156,7 +157,7 @@ public string? Secret } } - + _secret = value; } } @@ -457,7 +458,7 @@ internal static (CredentialPeriod period, string? issuer, string account) ParseL string account = parsedAccount.Last(); - return (period, issuer, account); + return (period, issuer, account); } /// @@ -481,7 +482,7 @@ public static Credential ParseUri(Uri uri) { if (uri == null) { - throw new ArgumentNullException(nameof(uri)); + throw new ArgumentNullException(nameof(uri)); } if (!uri.IsAbsoluteUri || uriScheme != uri.Scheme) @@ -502,7 +503,7 @@ public static Credential ParseUri(Uri uri) } NameValueCollection? parsedUri = HttpUtility.ParseQueryString(uriQuery); - + string? defaultIssuer = parsedUri["issuer"]; (string? issuer, string account) = ParseUriPath(uriPath, defaultIssuer); @@ -641,14 +642,14 @@ public bool Equals(Credential? credential) return false; } - return (_issuer == credential._issuer) - && (_accountName == credential._accountName) - && (_secret == credential._secret) - && (_digits == credential._digits) - && (_counter == credential._counter) - && (_type == credential._type) - && (_period == credential._period) - && (_algorithm == credential._algorithm); + return _issuer == credential._issuer + && _accountName == credential._accountName + && _secret == credential._secret + && _digits == credential._digits + && _counter == credential._counter + && _type == credential._type + && _period == credential._period + && _algorithm == credential._algorithm; } public static bool operator ==(Credential lhs, Credential rhs) diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Oath/OathSession.Credential.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Oath/OathSession.Credential.cs index 4d38e8a0..78731677 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Oath/OathSession.Credential.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Oath/OathSession.Credential.cs @@ -223,7 +223,7 @@ public void AddCredential(Credential credential) throw new InvalidOperationException(ExceptionMessages.TouchNotSupported); } - if (credential.Algorithm == HashAlgorithm.Sha512 && + if (credential.Algorithm == HashAlgorithm.Sha512 && !_yubiKeyDevice.HasFeature(YubiKeyFeature.OathSha512)) { throw new InvalidOperationException(ExceptionMessages.SHA512NotSupported); diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Oath/OathSession.Password.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Oath/OathSession.Password.cs index b33544a4..139948a9 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Oath/OathSession.Password.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Oath/OathSession.Password.cs @@ -14,7 +14,6 @@ using System; using System.Globalization; -using System.Linq; using System.Security; using Yubico.Core.Iso7816; using Yubico.YubiKey.Oath.Commands; @@ -49,8 +48,8 @@ public bool TryVerifyPassword() try { - if (KeyCollector!(keyEntryData) == true) { - + if (KeyCollector!(keyEntryData)) + { ReadOnlyMemory password = keyEntryData.GetCurrentValue(); var validateCommand = new ValidateCommand(password, _oathData); ValidateResponse verifyResponse = Connection.SendCommand(validateCommand); @@ -140,8 +139,9 @@ public bool TryVerifyPassword(ReadOnlyMemory password) { return verifyResponse.GetData(); } - if ((verifyResponse.StatusWord == SWConstants.InvalidCommandDataParameter) - || (verifyResponse.StatusWord == SWConstants.ReferenceDataUnusable)) + + if (verifyResponse.StatusWord == SWConstants.InvalidCommandDataParameter + || verifyResponse.StatusWord == SWConstants.ReferenceDataUnusable) { return false; } @@ -184,7 +184,7 @@ public void SetPassword() try { - if (KeyCollector!(keyEntryData) == true) + if (KeyCollector!(keyEntryData)) { ReadOnlyMemory currentPassword = keyEntryData.GetCurrentValue(); ReadOnlyMemory newPassword = keyEntryData.GetNewValue(); @@ -379,7 +379,7 @@ public void UnsetPassword() try { - if (KeyCollector!(keyEntryData) == true) + if (KeyCollector!(keyEntryData)) { if (!TryUnsetPassword(keyEntryData.GetCurrentValue())) { @@ -472,6 +472,7 @@ public void UnsetPassword() /// A boolean, true if the OATH application is unset, and /// false otherwise. /// - public bool TryUnsetPassword(ReadOnlyMemory password) => TrySetPassword(password, ReadOnlyMemory.Empty); + public bool TryUnsetPassword(ReadOnlyMemory password) => + TrySetPassword(password, ReadOnlyMemory.Empty); } } diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Otp/ChallengeResponseAlgorithm.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Otp/ChallengeResponseAlgorithm.cs index 5cab3ab9..5e07952d 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Otp/ChallengeResponseAlgorithm.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Otp/ChallengeResponseAlgorithm.cs @@ -23,7 +23,7 @@ public enum ChallengeResponseAlgorithm /// The default value for the enumeration. /// None = 0, - + /// /// The Yubico OTP mode takes a 6 byte challenge and creates a /// response using the Yubico OTP algorithm, where variable fields diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Otp/Commands/ConfigureNdefCommand.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Otp/Commands/ConfigureNdefCommand.cs index e61ad480..7ad3a0b1 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Otp/Commands/ConfigureNdefCommand.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Otp/Commands/ConfigureNdefCommand.cs @@ -28,7 +28,7 @@ public class ConfigureNdefCommand : IYubiKeyCommand private const int AccessCodeOffset = 56; private readonly Slot _ndefSlot; - private readonly byte[] _configurationBuffer; + private readonly byte[] _configurationBuffer; /// /// The required size for the AccessCode buffer. @@ -108,7 +108,7 @@ public ConfigureNdefCommand(Slot slot, ReadOnlySpan configuration, ReadOnl public CommandApdu CreateCommandApdu() => new CommandApdu() { Ins = OtpConstants.RequestSlotInstruction, - P1 = + P1 = _ndefSlot == Slot.ShortPress ? OtpConstants.ProgramNDEFShortPress : OtpConstants.ProgramNDEFLongPress, diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Otp/Commands/SetDeviceInfoCommand.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Otp/Commands/SetDeviceInfoCommand.cs index f9843cfe..f07f2a02 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Otp/Commands/SetDeviceInfoCommand.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Otp/Commands/SetDeviceInfoCommand.cs @@ -12,8 +12,8 @@ // See the License for the specific language governing permissions and // limitations under the License. -using Yubico.YubiKey.Management.Commands; using Yubico.Core.Iso7816; +using Yubico.YubiKey.Management.Commands; namespace Yubico.YubiKey.Otp.Commands { diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Otp/Commands/SetLegacyDeviceConfigCommand.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Otp/Commands/SetLegacyDeviceConfigCommand.cs index 3e7a8a5f..8405c469 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Otp/Commands/SetLegacyDeviceConfigCommand.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Otp/Commands/SetLegacyDeviceConfigCommand.cs @@ -12,8 +12,8 @@ // See the License for the specific language governing permissions and // limitations under the License. -using Yubico.YubiKey.Management.Commands; using Yubico.Core.Iso7816; +using Yubico.YubiKey.Management.Commands; namespace Yubico.YubiKey.Otp.Commands { diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Otp/NdefDataReader.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Otp/NdefDataReader.cs index 5a75c48c..0ae137ee 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Otp/NdefDataReader.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Otp/NdefDataReader.cs @@ -73,7 +73,7 @@ public NdefDataReader(ReadOnlySpan responseData) byte typeLength = responseData[TypeLengthOffset]; byte dataLength = responseData[DataLengthOffset]; const int validTypeLength = 1; - + if (typeLength != validTypeLength) { throw new NotSupportedException(ExceptionMessages.BadNdefRecordType); @@ -215,7 +215,7 @@ private static (Encoding encoding, bool bomPresent) DetectCorrectUtf16Encoding(R } // RFC 2781 does say to give preference to big endian, so I guess that'll be the tie-breaker. - return (score[0] >= score[1]) ? (Encoding.BigEndianUnicode, false) : (Encoding.Unicode, false); + return score[0] >= score[1] ? (Encoding.BigEndianUnicode, false) : (Encoding.Unicode, false); } } } diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Otp/Operations/OperationBase.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Otp/Operations/OperationBase.cs index 418a8b08..a4d9120c 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Otp/Operations/OperationBase.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Otp/Operations/OperationBase.cs @@ -31,7 +31,8 @@ public abstract class OperationBase where T : OperationBase /// /// The six-byte access code currently set to protect the OTP slot. /// - protected Span CurrentAccessCode { + protected Span CurrentAccessCode + { get => _currentAccessCode.Span; set => _currentAccessCode = value.ToArray(); } diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Otp/OtpSettings.ExtendedFlags.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Otp/OtpSettings.ExtendedFlags.cs index 7fb98118..1b0eede9 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Otp/OtpSettings.ExtendedFlags.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Otp/OtpSettings.ExtendedFlags.cs @@ -16,7 +16,7 @@ namespace Yubico.YubiKey.Otp { - public partial class OtpSettings where T: OperationBase + public partial class OtpSettings where T : OperationBase { /// /// Allows the serial number to be retrieved by holding down the touch button while inserting diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Pipelines/FidoTransform.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Pipelines/FidoTransform.cs index d297a8d3..901b9e84 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Pipelines/FidoTransform.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Pipelines/FidoTransform.cs @@ -90,10 +90,10 @@ public ResponseApdu Invoke(CommandApdu commandApdu, Type commandType, Type respo ResponseApdu responseApdu = responseByte switch { - Ctap1Message => new ResponseApdu(responseData), - CtapHidCbor => CtapToApduResponse.ToCtap2ResponseApdu(responseData), - CtapError => CtapToApduResponse.ToCtap1ResponseApdu(responseData), - _ => new ResponseApdu(responseData, SWConstants.Success), + Ctap1Message => new ResponseApdu(responseData), + CtapHidCbor => CtapToApduResponse.ToCtap2ResponseApdu(responseData), + CtapError => CtapToApduResponse.ToCtap1ResponseApdu(responseData), + _ => new ResponseApdu(responseData, SWConstants.Success), }; return responseApdu; @@ -137,14 +137,14 @@ private static byte GetPacketCmd(byte[] packet) => (byte)(packet[4] & ~0x80); private static int GetPacketBcnt(byte[] packet) => - (packet[5] << 8) | (packet[6]); + (packet[5] << 8) | packet[6]; private byte[] TransmitCommand(uint channelId, byte commandByte, byte[] data, out byte responseByte) { SendRequest(channelId, commandByte, data); byte cmdByte = commandByte; - if ((data.Length > 0) && (commandByte == CtapConstants.CtapHidCbor)) + if (data.Length > 0 && commandByte == CtapConstants.CtapHidCbor) { cmdByte = data[0]; } diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Pipelines/KeyboardTransform.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Pipelines/KeyboardTransform.cs index bbb95698..0f0542cc 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Pipelines/KeyboardTransform.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Pipelines/KeyboardTransform.cs @@ -13,13 +13,13 @@ // limitations under the License. using System; +using System.Diagnostics; using System.Globalization; using System.Threading; -using Yubico.YubiKey.Otp; using Yubico.Core.Devices.Hid; using Yubico.Core.Iso7816; -using System.Diagnostics; using Yubico.Core.Logging; +using Yubico.YubiKey.Otp; namespace Yubico.YubiKey.Pipelines { diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Pipelines/OtpErrorTransform.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Pipelines/OtpErrorTransform.cs index b44db208..7723e7e4 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Pipelines/OtpErrorTransform.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Pipelines/OtpErrorTransform.cs @@ -13,9 +13,9 @@ // limitations under the License. using System; -using Yubico.YubiKey.Otp.Commands; using Yubico.Core.Iso7816; using Yubico.Core.Logging; +using Yubico.YubiKey.Otp.Commands; namespace Yubico.YubiKey.Pipelines { diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Pipelines/Scp03ApduTransform.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Pipelines/Scp03ApduTransform.cs index db08f300..8f372e8b 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Pipelines/Scp03ApduTransform.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Pipelines/Scp03ApduTransform.cs @@ -14,10 +14,10 @@ using System; using System.Security.Cryptography; -using Yubico.YubiKey.Scp03.Commands; -using Yubico.YubiKey.Scp03; using Yubico.Core.Iso7816; using Yubico.YubiKey.Cryptography; +using Yubico.YubiKey.Scp03; +using Yubico.YubiKey.Scp03.Commands; namespace Yubico.YubiKey.Pipelines { diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/AesForManagementKey.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/AesForManagementKey.cs index 552aeac8..0188d1aa 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/AesForManagementKey.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/AesForManagementKey.cs @@ -113,15 +113,15 @@ public int TransformBlock(byte[] inputBuffer, int inputOffset, int inputCount, b { throw new ArgumentNullException(nameof(outputBuffer)); } - if ((inputCount == 0) || ((inputCount & 7) != 0)) + if (inputCount == 0 || (inputCount & 7) != 0) { throw new ArgumentException( string.Format( CultureInfo.CurrentCulture, ExceptionMessages.IncorrectPlaintextLength)); } - if ((inputOffset < 0) || ((inputBuffer.Length - inputOffset) < inputCount) || - (outputOffset < 0) || (outputBuffer.Length - outputOffset < inputCount)) + if (inputOffset < 0 || inputBuffer.Length - inputOffset < inputCount || + outputOffset < 0 || outputBuffer.Length - outputOffset < inputCount) { throw new ArgumentException( string.Format( diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/AuthenticateDecryptCommand.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/AuthenticateDecryptCommand.cs index 73061e69..eb7221e7 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/AuthenticateDecryptCommand.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/AuthenticateDecryptCommand.cs @@ -13,9 +13,9 @@ // limitations under the License. using System; -using System.Globalization; using System.Collections.Generic; using System.Collections.ObjectModel; +using System.Globalization; using System.Linq; using Yubico.Core.Iso7816; diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/AuthenticateKeyAgreeCommand.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/AuthenticateKeyAgreeCommand.cs index 9eb890be..f08d1881 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/AuthenticateKeyAgreeCommand.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/AuthenticateKeyAgreeCommand.cs @@ -13,8 +13,8 @@ // limitations under the License. using System; -using System.Globalization; using System.Collections.Generic; +using System.Globalization; using Yubico.Core.Iso7816; namespace Yubico.YubiKey.Piv.Commands diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/AuthenticateSignCommand.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/AuthenticateSignCommand.cs index 80fcff5c..2019d4e9 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/AuthenticateSignCommand.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/AuthenticateSignCommand.cs @@ -13,10 +13,10 @@ // limitations under the License. using System; -using System.Globalization; -using System.Security.Cryptography; using System.Collections.Generic; +using System.Globalization; using System.Linq; +using System.Security.Cryptography; using Yubico.Core.Iso7816; using Yubico.Core.Tlv; diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/ChangeReferenceDataCommand.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/ChangeReferenceDataCommand.cs index 7286ad5f..f371c294 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/ChangeReferenceDataCommand.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/ChangeReferenceDataCommand.cs @@ -13,8 +13,8 @@ // limitations under the License. using System; -using System.Globalization; using System.Collections.Generic; +using System.Globalization; using Yubico.Core.Iso7816; namespace Yubico.YubiKey.Piv.Commands @@ -104,7 +104,7 @@ public byte SlotNumber get => _slotNumber; set { - if ((value != PivSlot.Pin) && (value != PivSlot.Puk)) + if (value != PivSlot.Pin && value != PivSlot.Puk) { throw new ArgumentException( string.Format( @@ -170,8 +170,8 @@ public ChangeReferenceDataCommand(byte slotNumber, ReadOnlyMemory currentV { SlotNumber = slotNumber; - if ((PivPinUtilities.IsValidPinLength(currentValue.Length) == false) - || (PivPinUtilities.IsValidPinLength(newValue.Length) == false)) + if (PivPinUtilities.IsValidPinLength(currentValue.Length) == false + || PivPinUtilities.IsValidPinLength(newValue.Length) == false) { throw new ArgumentException( string.Format( diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/CompleteAuthenticateManagementKeyCommand.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/CompleteAuthenticateManagementKeyCommand.cs index f2a1b057..2ae7dc98 100755 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/CompleteAuthenticateManagementKeyCommand.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/CompleteAuthenticateManagementKeyCommand.cs @@ -15,9 +15,9 @@ using System; using System.Globalization; using System.Security.Cryptography; -using Yubico.YubiKey.Cryptography; using Yubico.Core.Iso7816; using Yubico.Core.Tlv; +using Yubico.YubiKey.Cryptography; namespace Yubico.YubiKey.Piv.Commands { diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/GenerateKeyPairCommand.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/GenerateKeyPairCommand.cs index 4c2d3197..3629b632 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/GenerateKeyPairCommand.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/GenerateKeyPairCommand.cs @@ -13,8 +13,8 @@ // limitations under the License. using System; -using System.Globalization; using System.Collections.Generic; +using System.Globalization; using System.Linq; using Yubico.Core.Iso7816; @@ -296,13 +296,13 @@ private byte[] BuildGenerateKeyPairApduData() int length = data.Length; int valueLength = algorithmCount + pinPolicyCount + touchPolicyCount; - if ((PinPolicy == PivPinPolicy.Default) || (PinPolicy == PivPinPolicy.None)) + if (PinPolicy == PivPinPolicy.Default || PinPolicy == PivPinPolicy.None) { Array.Copy(data, indexTouchPolicy, data, indexPinPolicy, touchPolicyCount); length -= pinPolicyCount; valueLength -= pinPolicyCount; } - if ((TouchPolicy == PivTouchPolicy.Default) || (TouchPolicy == PivTouchPolicy.None)) + if (TouchPolicy == PivTouchPolicy.Default || TouchPolicy == PivTouchPolicy.None) { length -= touchPolicyCount; valueLength -= touchPolicyCount; diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/GetDataCommand.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/GetDataCommand.cs index 4a7d393e..94308f30 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/GetDataCommand.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/GetDataCommand.cs @@ -13,10 +13,10 @@ // limitations under the License. using System; -using System.Collections.Generic; using System.Buffers.Binary; -using System.Linq; +using System.Collections.Generic; using System.Globalization; +using System.Linq; using Yubico.Core.Iso7816; namespace Yubico.YubiKey.Piv.Commands @@ -148,9 +148,9 @@ public int DataTag get => _tag; set { - if ((value < MinimumVendorTag) || (value > MaximumVendorTag)) + if (value < MinimumVendorTag || value > MaximumVendorTag) { - if ((value != DiscoveryTag) && (value != BiometricGroupTemplateTag)) + if (value != DiscoveryTag && value != BiometricGroupTemplateTag) { throw new ArgumentException( string.Format( diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/ImportAsymmetricKeyCommand.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/ImportAsymmetricKeyCommand.cs index 1b9d023c..d5cc536c 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/ImportAsymmetricKeyCommand.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/ImportAsymmetricKeyCommand.cs @@ -324,12 +324,12 @@ private byte[] BuildImportAsymmetricApduData() _privateKey.EncodedPrivateKey.CopyTo(apduData); Array.Copy(_policy, 0, apduData, offset, maximumPolicyLength); - if ((PinPolicy == PivPinPolicy.Default) || (PinPolicy == PivPinPolicy.None)) + if (PinPolicy == PivPinPolicy.Default || PinPolicy == PivPinPolicy.None) { Array.Copy(_policy, pinPolicyCount, apduData, offset, touchPolicyCount); length -= pinPolicyCount; } - if ((TouchPolicy == PivTouchPolicy.Default) || (TouchPolicy == PivTouchPolicy.None)) + if (TouchPolicy == PivTouchPolicy.Default || TouchPolicy == PivTouchPolicy.None) { length -= touchPolicyCount; } diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/InitializeAuthenticateManagementKeyResponse.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/InitializeAuthenticateManagementKeyResponse.cs index bc5065ec..f8073dce 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/InitializeAuthenticateManagementKeyResponse.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/InitializeAuthenticateManagementKeyResponse.cs @@ -117,7 +117,7 @@ public InitializeAuthenticateManagementKeyResponse(ResponseApdu responseApdu, Pi int authTag = authReader.PeekTag(); ReadOnlyMemory value = authReader.ReadValue(authTag); - if ((nestedTag != NestedTag) || ((authTag != MutualAuthTag) && (authTag != SingleAuthTag))) + if (nestedTag != NestedTag || (authTag != MutualAuthTag && authTag != SingleAuthTag)) { throw new MalformedYubiKeyResponseException() { diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/PutDataCommand.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/PutDataCommand.cs index a5e4391f..a55adfff 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/PutDataCommand.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/PutDataCommand.cs @@ -215,7 +215,7 @@ public int DataTag get => _tag; set { - if ((value < MinimumVendorTag) || (value > MaximumVendorTag)) + if (value < MinimumVendorTag || value > MaximumVendorTag) { if (value != BiometricGroupTemplateTag) { diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/ResetRetryCommand.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/ResetRetryCommand.cs index 01f8be18..0fdcb788 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/ResetRetryCommand.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/ResetRetryCommand.cs @@ -14,7 +14,6 @@ using System; using System.Globalization; -using System.Collections.Generic; using Yubico.Core.Iso7816; namespace Yubico.YubiKey.Piv.Commands @@ -91,23 +90,15 @@ public sealed class ResetRetryCommand : IYubiKeyCommand { private const byte PivResetRetryInstruction = 0x2C; - /// - /// Gets the YubiKeyApplication to which this command belongs. For this - /// command it's PIV. - /// - /// - /// YubiKeyApplication.Piv - /// - public YubiKeyApplication Application => YubiKeyApplication.Piv; + private readonly ReadOnlyMemory _newPin; private readonly ReadOnlyMemory _puk; - private readonly ReadOnlyMemory _newPin; - // The default constructor explicitly defined. We don't want it to be // used. // Note that there is no object-initializer constructor. All the // constructor args are secret byte arrays. + // ReSharper disable once UnusedMember.Local private ResetRetryCommand() { throw new NotImplementedException(); @@ -149,8 +140,8 @@ private ResetRetryCommand() /// public ResetRetryCommand(ReadOnlyMemory puk, ReadOnlyMemory newPin) { - if ((PivPinUtilities.IsValidPinLength(puk.Length) == false) - || (PivPinUtilities.IsValidPinLength(newPin.Length) == false)) + if (PivPinUtilities.IsValidPinLength(puk.Length) == false + || PivPinUtilities.IsValidPinLength(newPin.Length) == false) { throw new ArgumentException( string.Format( @@ -162,16 +153,26 @@ public ResetRetryCommand(ReadOnlyMemory puk, ReadOnlyMemory newPin) _newPin = newPin; } + /// + /// Gets the YubiKeyApplication to which this command belongs. For this + /// command it's PIV. + /// + /// + /// YubiKeyApplication.Piv + /// + public YubiKeyApplication Application => YubiKeyApplication.Piv; + /// - public CommandApdu CreateCommandApdu() => new CommandApdu - { - Ins = PivResetRetryInstruction, - P2 = PivSlot.Pin, - Data = PivPinUtilities.CopyTwoPinsWithPadding(_puk, _newPin), - }; + public CommandApdu CreateCommandApdu() => + new CommandApdu + { + Ins = PivResetRetryInstruction, + P2 = PivSlot.Pin, + Data = PivPinUtilities.CopyTwoPinsWithPadding(_puk, _newPin), + }; /// public ResetRetryResponse CreateResponseForApdu(ResponseApdu responseApdu) => - new ResetRetryResponse(responseApdu); + new ResetRetryResponse(responseApdu); } } diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/SetManagementKeyCommand.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/SetManagementKeyCommand.cs index d7143f12..9300984d 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/SetManagementKeyCommand.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/SetManagementKeyCommand.cs @@ -191,7 +191,7 @@ private SetManagementKeyCommand() /// The bytes that make up the new management key. /// public SetManagementKeyCommand(ReadOnlyMemory newKey) - : this (newKey, PivTouchPolicy.Default, PivAlgorithm.TripleDes) + : this(newKey, PivTouchPolicy.Default, PivAlgorithm.TripleDes) { } @@ -221,7 +221,7 @@ public SetManagementKeyCommand(ReadOnlyMemory newKey) /// The touch policy for the management key. /// public SetManagementKeyCommand(ReadOnlyMemory newKey, PivTouchPolicy touchPolicy) - : this (newKey, touchPolicy, PivAlgorithm.TripleDes) + : this(newKey, touchPolicy, PivAlgorithm.TripleDes) { } diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/TripleDesForManagementKey.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/TripleDesForManagementKey.cs index 1d92207f..88ca6f8a 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/TripleDesForManagementKey.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/TripleDesForManagementKey.cs @@ -102,9 +102,9 @@ internal sealed class TripleDesForManagementKey : ISymmetricForManagementKey // Byte length of the key data private const int ValidTripleDesKeyLength = 24; private const int ValidDesKeyLength = 8; - private const int KeyOffsetFirst = 0; + private const int KeyOffsetFirst = 0; private const int KeyOffsetSecond = 8; - private const int KeyOffsetThird = 16; + private const int KeyOffsetThird = 16; private const int TripleDesBlockSize = 8; @@ -206,15 +206,15 @@ public int TransformBlock(byte[] inputBuffer, int inputOffset, int inputCount, b { throw new ArgumentNullException(nameof(outputBuffer)); } - if ((inputCount == 0) || ((inputCount & 7) != 0)) + if (inputCount == 0 || (inputCount & 7) != 0) { throw new ArgumentException( string.Format( CultureInfo.CurrentCulture, ExceptionMessages.IncorrectPlaintextLength)); } - if ((inputOffset < 0) || ((inputBuffer.Length - inputOffset) < inputCount) || - (outputOffset < 0) || (outputBuffer.Length - outputOffset < inputCount)) + if (inputOffset < 0 || inputBuffer.Length - inputOffset < inputCount || + outputOffset < 0 || outputBuffer.Length - outputOffset < inputCount) { throw new ArgumentException( string.Format( @@ -225,7 +225,7 @@ public int TransformBlock(byte[] inputBuffer, int inputOffset, int inputCount, b _ = _cryptoTransform.TransformBlock(inputBuffer, inputOffset, inputCount, outputBuffer, outputOffset); - if ((!(_cryptoTransformA is null)) && (!(_cryptoTransformB is null))) + if (!(_cryptoTransformA is null) && !(_cryptoTransformB is null)) { _ = _cryptoTransformB.TransformBlock(outputBuffer, outputOffset, inputCount, outputBuffer, outputOffset); _ = _cryptoTransformA.TransformBlock(outputBuffer, outputOffset, inputCount, outputBuffer, outputOffset); diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/VerifyPinCommand.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/VerifyPinCommand.cs index 915de6b2..a6c28d0e 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/VerifyPinCommand.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/VerifyPinCommand.cs @@ -13,8 +13,8 @@ // limitations under the License. using System; -using System.Globalization; using System.Collections.Generic; +using System.Globalization; using Yubico.Core.Iso7816; namespace Yubico.YubiKey.Piv.Commands diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Objects/AdminData.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Objects/AdminData.cs index 7d0f8962..13463261 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Objects/AdminData.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Objects/AdminData.cs @@ -13,11 +13,11 @@ // limitations under the License. using System; -using System.Security.Cryptography; -using System.Globalization; using System.Buffers.Binary; -using Yubico.Core.Tlv; +using System.Globalization; +using System.Security.Cryptography; using Yubico.Core.Logging; +using Yubico.Core.Tlv; namespace Yubico.YubiKey.Piv.Objects { @@ -464,9 +464,9 @@ private bool ReadDate(TlvReader tlvReader, ref byte elementsRead) // property to be null. It was set to null when we called Clear // before decoding. bool isValid = tlvReader.TryReadValue(out ReadOnlyMemory theTime, DateTag); - isValid = isValid && (theTime.Length <= 8); + isValid = isValid && theTime.Length <= 8; - if (isValid && (theTime.Length > 0)) + if (isValid && theTime.Length > 0) { var cpyObj = new Memory(new byte[8]); theTime.CopyTo(cpyObj); diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Objects/CardCapabilityContainer.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Objects/CardCapabilityContainer.cs index 26de8638..bc065823 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Objects/CardCapabilityContainer.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Objects/CardCapabilityContainer.cs @@ -13,11 +13,11 @@ // limitations under the License. using System; -using System.Security.Cryptography; using System.Globalization; -using Yubico.YubiKey.Cryptography; -using Yubico.Core.Tlv; +using System.Security.Cryptography; using Yubico.Core.Logging; +using Yubico.Core.Tlv; +using Yubico.YubiKey.Cryptography; namespace Yubico.YubiKey.Piv.Objects { @@ -352,7 +352,7 @@ private bool TryReadUniqueId(bool isValid, TlvReader tlvReader) _log.LogInformation("Decode data into CardCapabilityContainer: UniqueId."); if (tlvReader.TryReadValue(out ReadOnlyMemory encodedUniqueId, UniqueCardIdTag)) { - if ((encodedUniqueId.Length == UniqueCardIdLength) && + if (encodedUniqueId.Length == UniqueCardIdLength && MemoryExtensions.SequenceEqual(encodedUniqueId.Slice(AidOffset, AidLength).Span, ApplicationIdentifier.Span)) { var dest = new Memory(_uniqueCardIdentifier); @@ -384,17 +384,17 @@ private bool TryReadFixedValues(bool isValid, TlvReader tlvReader) Tuple[] elementList = GetFixedTupleArray(); int index = 0; - while (returnValue && (index < elementList.Length)) + while (returnValue && index < elementList.Length) { if (elementList[index].Item2 == 0) { returnValue = tlvReader.TryReadValue(out ReadOnlyMemory currentValue, elementList[index].Item1) && - (currentValue.Length == elementList[index].Item2); + currentValue.Length == elementList[index].Item2; } else { returnValue = tlvReader.TryReadByte(out byte currentValue, elementList[index].Item1) && - (currentValue == elementList[index].Item3); + currentValue == elementList[index].Item3; } index++; diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Objects/CardholderUniqueId.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Objects/CardholderUniqueId.cs index f2ebd1c8..f232c378 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Objects/CardholderUniqueId.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Objects/CardholderUniqueId.cs @@ -13,11 +13,11 @@ // limitations under the License. using System; -using System.Security.Cryptography; using System.Globalization; -using Yubico.YubiKey.Cryptography; -using Yubico.Core.Tlv; +using System.Security.Cryptography; using Yubico.Core.Logging; +using Yubico.Core.Tlv; +using Yubico.YubiKey.Cryptography; namespace Yubico.YubiKey.Piv.Objects { @@ -340,9 +340,9 @@ private bool TryReadTrailingElements(bool isValid, TlvReader tlvReader) _log.LogInformation("Decode data into CardholderUniqueId: TrailingElements."); if (tlvReader.TryReadValue(out ReadOnlyMemory signature, SignatureTag)) { - if ((signature.Length == 0) && tlvReader.TryReadValue(out ReadOnlyMemory lrc, LrcTag)) + if (signature.Length == 0 && tlvReader.TryReadValue(out ReadOnlyMemory lrc, LrcTag)) { - if ((lrc.Length == 0) && !tlvReader.HasData) + if (lrc.Length == 0 && !tlvReader.HasData) { return true; } diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Objects/KeyHistory.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Objects/KeyHistory.cs index 1d7bcb04..baedf576 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Objects/KeyHistory.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Objects/KeyHistory.cs @@ -13,10 +13,10 @@ // limitations under the License. using System; -using System.Text; using System.Globalization; -using Yubico.Core.Tlv; +using System.Text; using Yubico.Core.Logging; +using Yubico.Core.Tlv; namespace Yubico.YubiKey.Piv.Objects { @@ -189,7 +189,7 @@ public override byte[] Encode() return new byte[] { 0x53, 0x00 }; } - if ((_onCardCerts == 0) && (_offCardCerts == 0) && (!(OffCardCertificateUrl is null))) + if (_onCardCerts == 0 && _offCardCerts == 0 && !(OffCardCertificateUrl is null)) { throw new InvalidOperationException( string.Format( @@ -314,7 +314,7 @@ private void SetOffCardCertUrl(Uri? urlValue) // the URL to null. Otherwise, leave it alone. private void SetOffCardUrlNullIfZeroCerts() { - if ((_onCardCerts == 0) &&(_offCardCerts == 0)) + if (_onCardCerts == 0 && _offCardCerts == 0) { _offCardCertUrl = null; _urlBytes = null; diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Objects/PinProtectedData.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Objects/PinProtectedData.cs index 99cb3b0a..6c0fb8dc 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Objects/PinProtectedData.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Objects/PinProtectedData.cs @@ -13,10 +13,10 @@ // limitations under the License. using System; -using System.Security.Cryptography; using System.Globalization; -using Yubico.Core.Tlv; +using System.Security.Cryptography; using Yubico.Core.Logging; +using Yubico.Core.Tlv; namespace Yubico.YubiKey.Piv.Objects { diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Objects/PivDataObject.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Objects/PivDataObject.cs index 5a0a49d4..a4c4ae8f 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Objects/PivDataObject.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Objects/PivDataObject.cs @@ -154,9 +154,9 @@ protected virtual bool IsValidAlternateTag(int dataTag) { if (dataTag != GetDefinedDataTag()) { - if ((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; } diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivDataTagExtensions.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivDataTagExtensions.cs index 52639792..17cc9f79 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivDataTagExtensions.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivDataTagExtensions.cs @@ -34,13 +34,14 @@ public static class PivDataTagExtensions /// A boolean, true if the tag is allowed to be used in PUT DATA, and /// false otherwise. /// - public static bool IsValidTagForPut(this PivDataTag tag) => tag switch - { - PivDataTag.Printed => false, - PivDataTag.Discovery => false, - PivDataTag.BiometricGroupTemplate => false, - _ => true, - }; + public static bool IsValidTagForPut(this PivDataTag tag) => + tag switch + { + PivDataTag.Printed => false, + PivDataTag.Discovery => false, + PivDataTag.BiometricGroupTemplate => false, + _ => true, + }; /// /// Is the given encoding valid for PUT DATA using the specified tag. @@ -63,6 +64,7 @@ public static class PivDataTagExtensions public static bool IsValidEncodingForPut(this PivDataTag tag, ReadOnlyMemory encoding) { TlvReader? tlvReader = GetTlvReader(tag, encoding); + if (tlvReader is null) { return false; @@ -70,6 +72,7 @@ public static bool IsValidEncodingForPut(this PivDataTag tag, ReadOnlyMemory encoding) { int expectedTag = PivPutDataTag; - if ((tag == PivDataTag.Discovery) || (tag == PivDataTag.BiometricGroupTemplate)) + + if (tag == PivDataTag.Discovery || tag == PivDataTag.BiometricGroupTemplate) { expectedTag = (int)tag; } @@ -309,7 +334,8 @@ public static bool IsValidEncodingForPut(this PivDataTag tag, ReadOnlyMemory value = tlvReader.ReadValue(expectedFormat[index]); - returnValue = expectedFormat[index + 1] != 0 ? - value.Length <= expectedFormat[index + 1] : value.Length == expectedFormat[index + 2]; + + returnValue = expectedFormat[index + 1] != 0 + ? value.Length <= expectedFormat[index + 1] + : value.Length == expectedFormat[index + 2]; index += 3; } diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivEccPrivateKey.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivEccPrivateKey.cs index e89f939f..89655331 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivEccPrivateKey.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivEccPrivateKey.cs @@ -101,7 +101,7 @@ public static PivEccPrivateKey CreateEccPrivateKey(ReadOnlyMemory encodedP { var tlvReader = new TlvReader(encodedPrivateKey); - if ((tlvReader.HasData == false) || (tlvReader.PeekTag() != EccTag)) + if (tlvReader.HasData == false || tlvReader.PeekTag() != EccTag) { throw new ArgumentException( string.Format( diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivEccPublicKey.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivEccPublicKey.cs index 04dad78e..d3ba079f 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivEccPublicKey.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivEccPublicKey.cs @@ -56,11 +56,6 @@ public sealed class PivEccPublicKey : PivPublicKey private Memory _publicPoint; - /// - /// Contains the public point: 04 || x-coordinate || y-coordinate. - /// - public ReadOnlySpan PublicPoint => _publicPoint.Span; - // The default constructor. We don't want it to be used by anyone outside // this class. private PivEccPublicKey() @@ -99,6 +94,11 @@ public PivEccPublicKey(ReadOnlySpan publicPoint) } } + /// + /// Contains the public point: 04 || x-coordinate || y-coordinate. + /// + public ReadOnlySpan PublicPoint => _publicPoint.Span; + /// /// Try to create a new instance of an ECC public key object based on the /// encoding. @@ -119,9 +119,8 @@ public PivEccPublicKey(ReadOnlySpan publicPoint) /// True if the method was able to create a new RSA public key object, /// false otherwise. /// - internal static bool TryCreate( - out PivPublicKey publicKeyObject, - ReadOnlyMemory encodedPublicKey) + internal static bool TryCreate(out PivPublicKey publicKeyObject, + ReadOnlyMemory encodedPublicKey) { var returnValue = new PivEccPublicKey(); publicKeyObject = returnValue; @@ -130,15 +129,18 @@ internal static bool TryCreate( { var tlvReader = new TlvReader(encodedPublicKey); int tag = tlvReader.PeekTag(2); + if (tag == PublicKeyTag) { tlvReader = tlvReader.ReadNestedTlv(tag); } ReadOnlyMemory value = null; - while (tlvReader.HasData == true) + + while (tlvReader.HasData) { tag = tlvReader.PeekTag(); + if (tag != EccTag) { return false; @@ -171,10 +173,12 @@ private bool LoadEccPublicKey(ReadOnlySpan publicPoint) { case EccP256PublicKeySize: Algorithm = PivAlgorithm.EccP256; + break; case EccP384PublicKeySize: Algorithm = PivAlgorithm.EccP384; + break; default: @@ -187,10 +191,12 @@ private bool LoadEccPublicKey(ReadOnlySpan publicPoint) } var tlvWriter = new TlvWriter(); + using (tlvWriter.WriteNestedTlv(PublicKeyTag)) { tlvWriter.WriteValue(EccTag, publicPoint); } + PivEncodedKey = tlvWriter.Encode(); // The Metadate encoded key is the contents of the nested. So set diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivMetadata.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivMetadata.cs index 512e4a83..acd280a2 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivMetadata.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivMetadata.cs @@ -13,10 +13,8 @@ // limitations under the License. using System; -using System.Collections.Generic; using System.Diagnostics; using System.Globalization; -using System.Linq; using Yubico.Core.Tlv; namespace Yubico.YubiKey.Piv @@ -140,56 +138,6 @@ public class PivMetadata private const int RetriesTag = 6; - /// - /// The slot for the metadata listed in this instance. - /// - public int Slot { get; private set; } - - /// - /// The algorithm of the key in the specified slot.
- /// Note that if a slot is empty, the Algorithm will be
- /// PivAlgorithm.None. - ///
- public PivAlgorithm Algorithm { get; private set; } - - /// - /// If the key is PIN, PUK, or management, is it the default value?
- /// If the key is asymmetric, is it the imported or generated?
- /// If the slot is empty, the status will be Unknown. - ///
- public PivKeyStatus KeyStatus { get; private set; } - - /// - /// The policy for requiring the PIN before operations using the key in - /// the given slot. - /// - public PivPinPolicy PinPolicy { get; private set; } - - /// - /// The policy for requiring touch before operations using the key in - /// the given slot. - /// - public PivTouchPolicy TouchPolicy { get; private set; } - - /// - /// The public key associated with the private key in the given slot. - /// - public PivPublicKey PublicKey { get; private set; } - - /// - /// The total number of wrong PINs or PUKs that can be entered before the - /// PIN or PUK will be locked. If the slot is not PIN or PUK, this value - /// will be -1, indicating the count is unknown. - /// - public int RetryCount { get; private set; } - - /// - /// How many PIN or PUK retries remain before the PIN or PUK will be - /// locked. If the slot is not PIN or PUK, this value will be -1, - /// indicating the count is unknown. - /// - public int RetriesRemaining { get; private set; } - /// /// The constructor that takes in the metadata encoding returned by the /// YubiKey in response to the Get metadata command, along with the slot. @@ -224,7 +172,7 @@ public PivMetadata(ReadOnlyMemory responseData, byte slotNumber) var tlvReader = new TlvReader(responseData); - while (tlvReader.HasData == true) + while (tlvReader.HasData) { int tag = tlvReader.PeekTag(); ReadOnlyMemory value = tlvReader.ReadValue(tag); @@ -241,36 +189,41 @@ public PivMetadata(ReadOnlyMemory responseData, byte slotNumber) // Algorithm // One byte, no more, no less. ThrowIfNotLength(value, 1); - Debug.Assert((value.Span[0] == 0xFF) || (value.Span[0] == 0x03) - || (value.Span[0] == 0x08) || (value.Span[0] == 0x0A) || (value.Span[0] == 0x0C) - || (value.Span[0] == 0x06) || (value.Span[0] == 0x07) - || (value.Span[0] == 0x11) || (value.Span[0] == 0x14)); + + Debug.Assert(value.Span[0] == 0xFF || value.Span[0] == 0x03 + || value.Span[0] == 0x08 || value.Span[0] == 0x0A || value.Span[0] == 0x0C + || value.Span[0] == 0x06 || value.Span[0] == 0x07 + || value.Span[0] == 0x11 || value.Span[0] == 0x14); Algorithm = (PivAlgorithm)value.Span[0]; + break; case PolicyTag: // Policy: PIN and touch policy // Two bytes, no more, no less. ThrowIfNotLength(value, 2); - Debug.Assert((value.Span[0] >= 0) && (value.Span[0] <= 3)); - Debug.Assert((value.Span[1] >= 0) && (value.Span[1] <= 3)); + Debug.Assert(value.Span[0] >= 0 && value.Span[0] <= 3); + Debug.Assert(value.Span[1] >= 0 && value.Span[1] <= 3); // If the value is 0, that means Default. Otherwise, the // value should be 1, 2, or 3 for Never, Once, and // Always with PIN policy, and 1, 2, or 3 for Never, // Always, and Cached with touch policy. PinPolicy = PivPinPolicy.Default; + if (value.Span[0] != 0) { PinPolicy = (PivPinPolicy)value.Span[0]; } TouchPolicy = PivTouchPolicy.Default; + if (value.Span[1] != 0) { TouchPolicy = (PivTouchPolicy)value.Span[1]; } + break; case OriginTag: @@ -278,14 +231,16 @@ public PivMetadata(ReadOnlyMemory responseData, byte slotNumber) // One byte, no more, no less. // 1 means generated, 2 means imported. ThrowIfNotLength(value, 1); - Debug.Assert((value.Span[0] == 1) || (value.Span[0] == 2)); + Debug.Assert(value.Span[0] == 1 || value.Span[0] == 2); KeyStatus = (PivKeyStatus)value.Span[0]; + break; case PublicTag: // Public: public key partner to the private key in the // slot PublicKey = PivPublicKey.Create(value); + break; case DefaultTag: @@ -295,10 +250,12 @@ public PivMetadata(ReadOnlyMemory responseData, byte slotNumber) ThrowIfNotLength(value, 1); KeyStatus = PivKeyStatus.Default; + if (value.Span[0] == 0) { KeyStatus = PivKeyStatus.NotDefault; } + break; case RetriesTag: @@ -309,11 +266,62 @@ public PivMetadata(ReadOnlyMemory responseData, byte slotNumber) RetryCount = (int)value.Span[0]; RetriesRemaining = (int)value.Span[1]; + break; } } } + /// + /// The slot for the metadata listed in this instance. + /// + public int Slot { get; private set; } + + /// + /// The algorithm of the key in the specified slot.
+ /// Note that if a slot is empty, the Algorithm will be
+ /// PivAlgorithm.None. + ///
+ public PivAlgorithm Algorithm { get; private set; } + + /// + /// If the key is PIN, PUK, or management, is it the default value?
+ /// If the key is asymmetric, is it the imported or generated?
+ /// If the slot is empty, the status will be Unknown. + ///
+ public PivKeyStatus KeyStatus { get; private set; } + + /// + /// The policy for requiring the PIN before operations using the key in + /// the given slot. + /// + public PivPinPolicy PinPolicy { get; private set; } + + /// + /// The policy for requiring touch before operations using the key in + /// the given slot. + /// + public PivTouchPolicy TouchPolicy { get; private set; } + + /// + /// The public key associated with the private key in the given slot. + /// + public PivPublicKey PublicKey { get; private set; } + + /// + /// The total number of wrong PINs or PUKs that can be entered before the + /// PIN or PUK will be locked. If the slot is not PIN or PUK, this value + /// will be -1, indicating the count is unknown. + /// + public int RetryCount { get; private set; } + + /// + /// How many PIN or PUK retries remain before the PIN or PUK will be + /// locked. If the slot is not PIN or PUK, this value will be -1, + /// indicating the count is unknown. + /// + public int RetriesRemaining { get; private set; } + private static void ThrowIfNotLength(ReadOnlyMemory value, int length) { if (value.Length != length) diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivPinUtilities.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivPinUtilities.cs index ac9881c7..080f4b39 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivPinUtilities.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivPinUtilities.cs @@ -93,7 +93,7 @@ internal static class PivPinUtilities /// True if pinLength is a valid PIV PIN length, or False otherwise. /// public static bool IsValidPinLength(int pinLength) => - (pinLength >= MinimumPinLength) && (pinLength <= MaximumPinLength); + pinLength >= MinimumPinLength && pinLength <= MaximumPinLength; /// /// Determine, based on the , what the @@ -201,8 +201,8 @@ public static byte[] CopySinglePinWithPadding(ReadOnlyMemory pin) /// public static byte[] CopyTwoPinsWithPadding(ReadOnlyMemory firstPin, ReadOnlyMemory secondPin) { - if ((IsValidPinLength(firstPin.Length) == false) - || (IsValidPinLength(secondPin.Length) == false)) + if (IsValidPinLength(firstPin.Length) == false + || IsValidPinLength(secondPin.Length) == false) { throw new ArgumentException( string.Format( diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivPrivateKey.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivPrivateKey.cs index 46d77c87..e294c230 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivPrivateKey.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivPrivateKey.cs @@ -118,7 +118,7 @@ public static PivPrivateKey Create(ReadOnlyMemory encodedPrivateKey) tag = encodedPrivateKey.Span[0]; } - switch(tag) + switch (tag) { default: throw new ArgumentException( diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivRsaPrivateKey.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivRsaPrivateKey.cs index 5ced69cb..2e680dc4 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivRsaPrivateKey.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivRsaPrivateKey.cs @@ -144,8 +144,8 @@ public PivRsaPrivateKey( ExceptionMessages.InvalidPrivateKeyData)), }; - if ((primeQ.Length != primeP.Length) || (exponentP.Length != primeP.Length) - || (exponentQ.Length != primeP.Length) || (coefficient.Length != primeP.Length)) + if (primeQ.Length != primeP.Length || exponentP.Length != primeP.Length + || exponentQ.Length != primeP.Length || coefficient.Length != primeP.Length) { throw new ArgumentException( string.Format( @@ -200,7 +200,7 @@ public static PivRsaPrivateKey CreateRsaPrivateKey(ReadOnlyMemory encodedP int tag = tlvReader.PeekTag(); ReadOnlyMemory temp = tlvReader.ReadValue(tag); - if ((tag <= 0) || (tag > CrtComponentCount)) + if (tag <= 0 || tag > CrtComponentCount) { continue; } diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivRsaPublicKey.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivRsaPublicKey.cs index b422cc32..958b1087 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivRsaPublicKey.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivRsaPublicKey.cs @@ -76,18 +76,8 @@ public sealed class PivRsaPublicKey : PivPublicKey private Memory _modulus; - /// - /// Contains the modulus portion of the RSA public key. - /// - public ReadOnlySpan Modulus => _modulus.Span; - private Memory _publicExponent; - /// - /// Contains the public exponent portion of the RSA public key. - /// - public ReadOnlySpan PublicExponent => _publicExponent.Span; - // The default constructor. We don't want it to be used by anyone outside // this class. private PivRsaPublicKey() @@ -120,6 +110,16 @@ public PivRsaPublicKey(ReadOnlySpan modulus, ReadOnlySpan publicExpo } } + /// + /// Contains the modulus portion of the RSA public key. + /// + public ReadOnlySpan Modulus => _modulus.Span; + + /// + /// Contains the public exponent portion of the RSA public key. + /// + public ReadOnlySpan PublicExponent => _publicExponent.Span; + /// /// Try to create a new instance of an RSA public key object based on the /// encoding. @@ -140,9 +140,8 @@ public PivRsaPublicKey(ReadOnlySpan modulus, ReadOnlySpan publicExpo /// True if the method was able to create a new RSA public key object, /// false otherwise. /// - internal static bool TryCreate( - out PivPublicKey publicKeyObject, - ReadOnlyMemory encodedPublicKey) + internal static bool TryCreate(out PivPublicKey publicKeyObject, + ReadOnlyMemory encodedPublicKey) { var returnValue = new PivRsaPublicKey(); publicKeyObject = returnValue; @@ -151,6 +150,7 @@ internal static bool TryCreate( { var tlvReader = new TlvReader(encodedPublicKey); int tag = tlvReader.PeekTag(2); + if (tag == PublicKeyTag) { tlvReader = tlvReader.ReadNestedTlv(tag); @@ -158,18 +158,21 @@ internal static bool TryCreate( var valueArray = new ReadOnlyMemory[PublicComponentCount]; - while (tlvReader.HasData == true) + while (tlvReader.HasData) { int valueIndex; tag = tlvReader.PeekTag(); + switch (tag) { case ModulusTag: valueIndex = ModulusIndex; + break; case ExponentTag: valueIndex = ExponentIndex; + break; default: @@ -201,15 +204,18 @@ internal static bool TryCreate( private bool LoadRsaPublicKey(ReadOnlySpan modulus, ReadOnlySpan publicExponent) { int sliceIndex = SliceIndex1024; + switch (modulus.Length) { case Rsa1024BlockSize: Algorithm = PivAlgorithm.Rsa1024; + break; case Rsa2048BlockSize: Algorithm = PivAlgorithm.Rsa2048; sliceIndex = SliceIndex2048; + break; default: @@ -229,11 +235,13 @@ private bool LoadRsaPublicKey(ReadOnlySpan modulus, ReadOnlySpan pub } var tlvWriter = new TlvWriter(); + using (tlvWriter.WriteNestedTlv(PublicKeyTag)) { tlvWriter.WriteValue(ModulusTag, modulus); tlvWriter.WriteValue(ExponentTag, _exponentF4); } + PivEncodedKey = tlvWriter.Encode(); // The Metadate encoded key is the contents of the nested. So set @@ -256,12 +264,14 @@ private bool IsExponentF4(ReadOnlySpan exponent) } int index = 0; + while (exponent.Length - index > ValidExponentLength) { if (exponent[index] != 0) { return false; } + index++; } diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.Attestation.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.Attestation.cs index 493f81af..426ad163 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.Attestation.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.Attestation.cs @@ -17,9 +17,9 @@ using System.Security; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; -using Yubico.YubiKey.Piv.Commands; -using Yubico.YubiKey.Cryptography; using Yubico.Core.Tlv; +using Yubico.YubiKey.Cryptography; +using Yubico.YubiKey.Piv.Commands; namespace Yubico.YubiKey.Piv { @@ -436,7 +436,7 @@ private static bool IsCert(X509Certificate2 certificate, out byte[] certDer) } } - return (certDer.Length > 0) && (certDer.Length < MaximumCertDerLength); + return certDer.Length > 0 && certDer.Length < MaximumCertDerLength; } // Does the cert in the object share the algorithm and key size? @@ -511,8 +511,8 @@ private static bool IsCertNameAndValidity(bool isValidCert, byte[] certDer) if (index >= tags.Length) { - returnValue = (value[4].Length < MaximumValidityValueLength) && - (value[5].Length < MaximumNameValueLength); + returnValue = value[4].Length < MaximumValidityValueLength && + value[5].Length < MaximumNameValueLength; } } } diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.Crypto.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.Crypto.cs index da62eb55..4a2ea8c4 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.Crypto.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.Crypto.cs @@ -24,7 +24,6 @@ namespace Yubico.YubiKey.Piv // agree. public sealed partial class PivSession : IDisposable { - /// /// Create a digital signature using the key in the given slot. /// @@ -363,6 +362,7 @@ public byte[] KeyAgree(byte slotNumber, PivPublicKey correspondentPublicKey) { throw new ArgumentNullException(nameof(correspondentPublicKey)); } + if (!correspondentPublicKey.Algorithm.IsEcc()) { throw new ArgumentException( @@ -389,11 +389,10 @@ public byte[] KeyAgree(byte slotNumber, PivPublicKey correspondentPublicKey) // Common code, this performs either Signing, Decryption, or Key // Agreement. Just pass in the actual command to run, along with some // other information. - private byte[] PerformPrivateKeyOperation( - byte slotNumber, - IYubiKeyCommand> command, - PivAlgorithm algorithm, - string algorithmExceptionMessage) + private byte[] PerformPrivateKeyOperation(byte slotNumber, + IYubiKeyCommand> command, + PivAlgorithm algorithm, + string algorithmExceptionMessage) { bool pinRequired = true; @@ -428,8 +427,8 @@ private byte[] PerformPrivateKeyOperation( // PIN is not required. // The only other case is Always which means we set the // pinRequired to true, but we init that variable to true. - if ((metadata.PinPolicy == PivPinPolicy.Never) || - ((metadata.PinPolicy == PivPinPolicy.Once) && PinVerified)) + if (metadata.PinPolicy == PivPinPolicy.Never || + (metadata.PinPolicy == PivPinPolicy.Once && PinVerified)) { pinRequired = false; } @@ -466,7 +465,7 @@ private byte[] PerformPrivateKeyOperation( } } - if (pinRequired == true) + if (pinRequired) { // This is the verify method that will throw an exception if the // user cancels. diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.KeyPairs.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.KeyPairs.cs index 0b8643d7..f59231b0 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.KeyPairs.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.KeyPairs.cs @@ -16,8 +16,8 @@ using System.Globalization; using System.Security; using System.Security.Cryptography.X509Certificates; -using Yubico.YubiKey.Piv.Commands; using Yubico.Core.Tlv; +using Yubico.YubiKey.Piv.Commands; namespace Yubico.YubiKey.Piv { @@ -124,11 +124,10 @@ public sealed partial class PivSession : IDisposable /// Mutual authentication was performed and the YubiKey was not /// authenticated. /// - public PivPublicKey GenerateKeyPair( - byte slotNumber, - PivAlgorithm algorithm, - PivPinPolicy pinPolicy = PivPinPolicy.Default, - PivTouchPolicy touchPolicy = PivTouchPolicy.Default) + public PivPublicKey GenerateKeyPair(byte slotNumber, + PivAlgorithm algorithm, + PivPinPolicy pinPolicy = PivPinPolicy.Default, + PivTouchPolicy touchPolicy = PivTouchPolicy.Default) { if (ManagementKeyAuthenticated == false) { @@ -137,6 +136,7 @@ public PivPublicKey GenerateKeyPair( var generateCommand = new GenerateKeyPairCommand(slotNumber, algorithm, pinPolicy, touchPolicy); GenerateKeyPairResponse generateResponse = Connection.SendCommand(generateCommand); + return generateResponse.GetData(); } @@ -229,11 +229,10 @@ public PivPublicKey GenerateKeyPair( /// Mutual authentication was performed and the YubiKey was not /// authenticated. /// - public void ImportPrivateKey( - byte slotNumber, - PivPrivateKey privateKey, - PivPinPolicy pinPolicy = PivPinPolicy.Default, - PivTouchPolicy touchPolicy = PivTouchPolicy.Default) + public void ImportPrivateKey(byte slotNumber, + PivPrivateKey privateKey, + PivPinPolicy pinPolicy = PivPinPolicy.Default, + PivTouchPolicy touchPolicy = PivTouchPolicy.Default) { if (ManagementKeyAuthenticated == false) { @@ -242,6 +241,7 @@ public void ImportPrivateKey( var importCommand = new ImportAsymmetricKeyCommand(privateKey, slotNumber, pinPolicy, touchPolicy); ImportAsymmetricKeyResponse importResponse = Connection.SendCommand(importCommand); + if (importResponse.Status != ResponseStatus.Success) { throw new InvalidOperationException(importResponse.StatusMessage); @@ -332,16 +332,19 @@ public void ImportCertificate(byte slotNumber, X509Certificate2 certificate) byte[] certDer = certificate.GetRawCertData(); var tlvWriter = new TlvWriter(); + using (tlvWriter.WriteNestedTlv(PivEncodingTag)) { tlvWriter.WriteValue(PivCertTag, certDer); tlvWriter.WriteByte(PivCompressionTag, 0); tlvWriter.WriteValue(PivLrcTag, null); } + byte[] encodedCert = tlvWriter.Encode(); var putCommand = new PutDataCommand((int)dataTag, encodedCert); PutDataResponse putResponse = Connection.SendCommand(putCommand); + if (putResponse.Status != ResponseStatus.Success) { throw new InvalidOperationException(putResponse.StatusMessage); @@ -395,10 +398,12 @@ public X509Certificate2 GetCertificate(byte slotNumber) var tlvReader = new TlvReader(encodedCertData); bool isValid = tlvReader.TryReadNestedTlv(out TlvReader nestedReader, PivEncodingTag); - if (isValid == true) + + if (isValid) { isValid = nestedReader.TryReadValue(out ReadOnlyMemory certData, PivCertTag); - if (isValid == true) + + if (isValid) { return new X509Certificate2(certData.ToArray()); } @@ -415,7 +420,7 @@ public X509Certificate2 GetCertificate(byte slotNumber) // will map the slot number to the appropriate DataTag. private static PivDataTag GetCertDataTagFromSlotNumber(byte slotNumber) { - if ((slotNumber >= PivSlot.Retired1) && (slotNumber <= PivSlot.Retired20)) + if (slotNumber >= PivSlot.Retired1 && slotNumber <= PivSlot.Retired20) { return PivDataTag.Retired1 + (slotNumber - PivSlot.Retired1); } diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.ManagementKey.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.ManagementKey.cs index af91b192..2059325a 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.ManagementKey.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.ManagementKey.cs @@ -13,11 +13,10 @@ // limitations under the License. using System; -using System.Security; using System.Globalization; -using Yubico.YubiKey.Piv.Commands; -using Yubico.YubiKey.Piv.Objects; +using System.Security; using Yubico.Core.Logging; +using Yubico.YubiKey.Piv.Commands; namespace Yubico.YubiKey.Piv { @@ -239,9 +238,11 @@ public sealed partial class PivSession : IDisposable /// public bool TryAuthenticateManagementKey(bool mutualAuthentication = true) { - _log.LogInformation($"Try to authenticate the management key: {(mutualAuthentication == true ? "mutual" : "single")} auth."); + _log.LogInformation( + $"Try to authenticate the management key: {(mutualAuthentication ? "mutual" : "single")} auth."); PivPinOnlyMode currentMode = TryAuthenticatePinOnly(true); + if (currentMode.HasFlag(PivPinOnlyMode.PinProtected) || currentMode.HasFlag(PivPinOnlyMode.PinDerived)) { return true; @@ -309,7 +310,9 @@ private bool TryAuthenticateWithKeyCollector(bool mutualAuthentication) /// public void AuthenticateManagementKey(bool mutualAuthentication = true) { - _log.LogInformation($"Authenticate the management key: {(mutualAuthentication == true ? "mutual" : "single")} auth."); + _log.LogInformation( + $"Authenticate the management key: {(mutualAuthentication ? "mutual" : "single")} auth."); + if (TryAuthenticateManagementKey(mutualAuthentication) == false) { throw new OperationCanceledException( @@ -671,6 +674,7 @@ public bool TryChangeManagementKey(PivTouchPolicy touchPolicy, PivAlgorithm newK if (setResponse.Status == ResponseStatus.Success) { ManagementKeyAlgorithm = newKeyAlgorithm; + return true; } @@ -685,6 +689,7 @@ public bool TryChangeManagementKey(PivTouchPolicy touchPolicy, PivAlgorithm newK keyEntryData.Clear(); keyEntryData.Request = KeyEntryRequest.Release; + if (!(KeyCollector is null)) { _ = KeyCollector(keyEntryData); @@ -820,10 +825,9 @@ public void ChangeManagementKey(PivTouchPolicy touchPolicy, PivAlgorithm newKeyA /// Mutual authentication was performed and the YubiKey was not /// authenticated. /// - public bool TryChangeManagementKey( - ReadOnlyMemory currentKey, - ReadOnlyMemory newKey, - PivTouchPolicy touchPolicy = PivTouchPolicy.Default) => + public bool TryChangeManagementKey(ReadOnlyMemory currentKey, + ReadOnlyMemory newKey, + PivTouchPolicy touchPolicy = PivTouchPolicy.Default) => TryChangeManagementKey(currentKey, newKey, touchPolicy, PivAlgorithm.TripleDes); /// @@ -883,11 +887,10 @@ public bool TryChangeManagementKey( /// Mutual authentication was performed and the YubiKey was not /// authenticated. /// - public bool TryChangeManagementKey( - ReadOnlyMemory currentKey, - ReadOnlyMemory newKey, - PivTouchPolicy touchPolicy, - PivAlgorithm newKeyAlgorithm) + public bool TryChangeManagementKey(ReadOnlyMemory currentKey, + ReadOnlyMemory newKey, + PivTouchPolicy touchPolicy, + PivAlgorithm newKeyAlgorithm) { CheckManagementKeyAlgorithm(newKeyAlgorithm, true); @@ -896,11 +899,10 @@ public bool TryChangeManagementKey( // Try to change the management key, even if the YubiKey is set to // PIN-derived. - private bool TryForcedChangeManagementKey( - ReadOnlyMemory currentKey, - ReadOnlyMemory newKey, - PivTouchPolicy touchPolicy, - PivAlgorithm newKeyAlgorithm) + private bool TryForcedChangeManagementKey(ReadOnlyMemory currentKey, + ReadOnlyMemory newKey, + PivTouchPolicy touchPolicy, + PivAlgorithm newKeyAlgorithm) { if (TryAuthenticateManagementKey(currentKey, true)) { @@ -910,6 +912,7 @@ private bool TryForcedChangeManagementKey( if (setResponse.Status == ResponseStatus.Success) { ManagementKeyAlgorithm = newKeyAlgorithm; + return true; } } @@ -934,6 +937,7 @@ private void CheckManagementKeyAlgorithm(PivAlgorithm algorithm, bool checkMode) if (checkMode) { PivPinOnlyMode mode = GetPinOnlyMode(); + if (mode.HasFlag(PivPinOnlyMode.PinProtected) || mode.HasFlag(PivPinOnlyMode.PinDerived)) { throw new InvalidOperationException( @@ -944,16 +948,19 @@ private void CheckManagementKeyAlgorithm(PivAlgorithm algorithm, bool checkMode) } bool isValid = false; + switch (algorithm) { case PivAlgorithm.TripleDes: isValid = true; + break; case PivAlgorithm.Aes128: case PivAlgorithm.Aes192: case PivAlgorithm.Aes256: isValid = _yubiKeyDevice.HasFeature(YubiKeyFeature.PivAesManagementKey); + break; default: @@ -996,10 +1003,10 @@ private bool TryAuthenticateWithKeyCollector(bool mutualAuthentication, KeyEntry ManagementKeyAuthenticationResult = AuthenticateManagementKeyResult.Unauthenticated; ManagementKeyAuthenticated = false; - while (KeyCollector(keyEntryData) == true) + while (KeyCollector(keyEntryData)) { if (ManagementKeyAuthenticated = TryAuthenticateManagementKey( - mutualAuthentication, keyEntryData.GetCurrentValue().Span, ManagementKeyAlgorithm)) + mutualAuthentication, keyEntryData.GetCurrentValue().Span, ManagementKeyAlgorithm)) { return true; } @@ -1017,10 +1024,9 @@ private bool TryAuthenticateWithKeyCollector(bool mutualAuthentication, KeyEntry // if the auth succeeds. // If auth works, return true, otherwise, return false. // Throw an exception if the YubiKey fails to auth. - private bool TryAuthenticateManagementKey( - bool mutualAuthentication, - ReadOnlySpan mgmtKey, - PivAlgorithm algorithm) + private bool TryAuthenticateManagementKey(bool mutualAuthentication, + ReadOnlySpan mgmtKey, + PivAlgorithm algorithm) { var initCommand = new InitializeAuthenticateManagementKeyCommand(mutualAuthentication, algorithm); InitializeAuthenticateManagementKeyResponse initResponse = Connection.SendCommand(initCommand); @@ -1029,6 +1035,7 @@ private bool TryAuthenticateManagementKey( CompleteAuthenticateManagementKeyResponse completeResponse = Connection.SendCommand(completeCommand); ManagementKeyAuthenticationResult = completeResponse.GetData(); + if (completeResponse.Status == ResponseStatus.Success) { // If Success, there are three possibilities, (1) this is @@ -1037,7 +1044,8 @@ private bool TryAuthenticateManagementKey( // off-card app authenticated, but the YubiKey itself did // not. // If case (3), throw an exception. - if (ManagementKeyAuthenticationResult == AuthenticateManagementKeyResult.MutualYubiKeyAuthenticationFailed) + if (ManagementKeyAuthenticationResult == + AuthenticateManagementKeyResult.MutualYubiKeyAuthenticationFailed) { throw new SecurityException( string.Format( diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.Msroots.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.Msroots.cs index 82c05bf2..aa373749 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.Msroots.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.Msroots.cs @@ -13,11 +13,11 @@ // limitations under the License. using System; -using System.Security; -using System.IO; using System.Globalization; -using Yubico.YubiKey.Piv.Commands; +using System.IO; +using System.Security; using Yubico.Core.Tlv; +using Yubico.YubiKey.Piv.Commands; namespace Yubico.YubiKey.Piv { @@ -329,7 +329,7 @@ private int CheckWriteLength(string contentsName, long length) { maxLength = NewMaximumObjectLength; } - if (length > (maxLength * MsrootsObjectCount)) + if (length > maxLength * MsrootsObjectCount) { throw new ArgumentOutOfRangeException( contentsName, length, diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.Objects.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.Objects.cs index 7017301a..204b581e 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.Objects.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.Objects.cs @@ -15,9 +15,9 @@ using System; using System.Globalization; using System.Security.Cryptography; +using Microsoft.Extensions.Logging; using Yubico.YubiKey.Piv.Commands; using Yubico.YubiKey.Piv.Objects; -using Microsoft.Extensions.Logging; namespace Yubico.YubiKey.Piv { diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.Pin.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.Pin.cs index 48d85024..4f384073 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.Pin.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.Pin.cs @@ -13,12 +13,11 @@ // limitations under the License. using System; -using System.Security; using System.Globalization; -using System.Security.Cryptography; +using System.Security; +using Yubico.Core.Logging; using Yubico.YubiKey.Piv.Commands; using Yubico.YubiKey.Piv.Objects; -using Yubico.Core.Logging; namespace Yubico.YubiKey.Piv { @@ -121,6 +120,7 @@ public sealed partial class PivSession : IDisposable public bool TryVerifyPin() { _log.LogInformation("Try to verify the PIV PIN with KeyCollector."); + if (KeyCollector is null) { throw new InvalidOperationException( @@ -138,7 +138,7 @@ public bool TryVerifyPin() try { - while (KeyCollector(keyEntryData) == true) + while (KeyCollector(keyEntryData)) { if (TryVerifyPin(keyEntryData.GetCurrentValue(), out int? retriesRemaining)) { @@ -185,6 +185,7 @@ public bool TryVerifyPin() public void VerifyPin() { _log.LogInformation("Verify the PIV PIN."); + if (TryVerifyPin() == false) { throw new OperationCanceledException( @@ -402,7 +403,8 @@ public bool TryVerifyPin(ReadOnlyMemory pin, out int? retriesRemaining) /// public void ChangePinAndPukRetryCounts(byte newRetryCountPin, byte newRetryCountPuk) { - _log.LogInformation("Change the PIV PIN and PUK retry counts: {PinCount}, {PukCount}.", newRetryCountPin, newRetryCountPuk); + _log.LogInformation("Change the PIV PIN and PUK retry counts: {PinCount}, {PukCount}.", newRetryCountPin, + newRetryCountPuk); // This will validate the input. var setRetriesCommand = new SetPinRetriesCommand(newRetryCountPin, newRetryCountPuk); @@ -431,12 +433,14 @@ public void ChangePinAndPukRetryCounts(byte newRetryCountPin, byte newRetryCount { AuthenticateManagementKey(); } + if (!PinVerified) { VerifyPin(); } SetPinRetriesResponse setRetriesResponse = Connection.SendCommand(setRetriesCommand); + if (setRetriesResponse.Status != ResponseStatus.Success) { throw new InvalidOperationException(setRetriesResponse.StatusMessage); @@ -447,6 +451,7 @@ public void ChangePinAndPukRetryCounts(byte newRetryCountPin, byte newRetryCount // By passing Empty, this method will use the default PIN. SetPinOnlyMode(ReadOnlyMemory.Empty, mode, out _); } + UpdateAdminData(); } @@ -514,14 +519,15 @@ public void ChangePinAndPukRetryCounts(byte newRetryCountPin, byte newRetryCount /// /// The remaining retries count indicates the PIN is blocked. /// - public bool TryChangePinAndPukRetryCounts( - ReadOnlyMemory managementKey, - ReadOnlyMemory pin, - byte newRetryCountPin, - byte newRetryCountPuk, - out int? retriesRemaining) + public bool TryChangePinAndPukRetryCounts(ReadOnlyMemory managementKey, + ReadOnlyMemory pin, + byte newRetryCountPin, + byte newRetryCountPuk, + out int? retriesRemaining) { - _log.LogInformation("Try to change the PIV PIN and PUK retry counts: {PinCount}, {PukCount} with supplied mgmt key and PIN.", newRetryCountPin, newRetryCountPuk); + _log.LogInformation( + "Try to change the PIV PIN and PUK retry counts: {PinCount}, {PukCount} with supplied mgmt key and PIN.", + newRetryCountPin, newRetryCountPuk); // This will validate the input. var setRetriesCommand = new SetPinRetriesCommand(newRetryCountPin, newRetryCountPuk); @@ -549,6 +555,7 @@ public bool TryChangePinAndPukRetryCounts( // By passing Empty, this method will use the default PIN. SetPinOnlyMode(ReadOnlyMemory.Empty, mode, out _); } + UpdateAdminData(); return true; @@ -660,6 +667,7 @@ public bool TryChangePinAndPukRetryCounts( public bool TryChangePin() { _log.LogInformation("Try to change the PIV PIN with KeyCollector."); + if (TryGetChangePinMode(ReadOnlyMemory.Empty, out PivPinOnlyMode mode, out _)) { return TryChangeReference(KeyEntryRequest.ChangePivPin, ChangePinOrPuk, mode); @@ -693,6 +701,7 @@ public bool TryChangePin() public void ChangePin() { _log.LogInformation("Change the PIV PIN."); + if (!TryChangePin()) { throw new OperationCanceledException( @@ -768,9 +777,11 @@ public void ChangePin() /// /// The remaining retries count indicates the PIN is blocked. /// - public bool TryChangePin(ReadOnlyMemory currentPin, ReadOnlyMemory newPin, out int? retriesRemaining) + public bool TryChangePin(ReadOnlyMemory currentPin, ReadOnlyMemory newPin, + out int? retriesRemaining) { _log.LogInformation("Try to change the PIV PIN with supplied PINs."); + if (TryGetChangePinMode(currentPin, out PivPinOnlyMode mode, out retriesRemaining)) { var changeCommand = new ChangeReferenceDataCommand(PivSlot.Pin, currentPin, newPin); @@ -782,6 +793,7 @@ public bool TryChangePin(ReadOnlyMemory currentPin, ReadOnlyMemory n { SetPinOnlyMode(newPin, mode, out retriesRemaining); } + UpdateAdminData(); return true; @@ -886,6 +898,7 @@ public bool TryChangePin(ReadOnlyMemory currentPin, ReadOnlyMemory n public bool TryChangePuk() { _log.LogInformation("Try to change the PIV PUK with KeyCollector."); + return TryChangeReference(KeyEntryRequest.ChangePivPuk, ChangePinOrPuk, PivPinOnlyMode.None); } @@ -914,6 +927,7 @@ public bool TryChangePuk() public void ChangePuk() { _log.LogInformation("Change the PIV PUK."); + if (TryChangeReference(KeyEntryRequest.ChangePivPuk, ChangePinOrPuk, PivPinOnlyMode.None) == false) { throw new OperationCanceledException( @@ -965,7 +979,8 @@ public void ChangePuk() /// /// The remaining retries count indicates the PUK is blocked. /// - public bool TryChangePuk(ReadOnlyMemory currentPuk, ReadOnlyMemory newPuk, out int? retriesRemaining) + public bool TryChangePuk(ReadOnlyMemory currentPuk, ReadOnlyMemory newPuk, + out int? retriesRemaining) { _log.LogInformation("Try to change the PIV PUK with supplied PUKs."); var changeCommand = new ChangeReferenceDataCommand(PivSlot.Puk, currentPuk, newPuk); @@ -1083,6 +1098,7 @@ public bool TryChangePuk(ReadOnlyMemory currentPuk, ReadOnlyMemory n public bool TryResetPin() { _log.LogInformation("Try to reset the PIV PIN using the PIV PUK with KeyCollector."); + if (TryGetChangePinMode(ReadOnlyMemory.Empty, out PivPinOnlyMode mode, out _)) { return TryChangeReference(KeyEntryRequest.ResetPivPinWithPuk, ResetPin, mode); @@ -1121,6 +1137,7 @@ public bool TryResetPin() public void ResetPin() { _log.LogInformation("Reset the PIV PIN using the PIV PUK."); + if (TryChangeReference(KeyEntryRequest.ResetPivPinWithPuk, ResetPin, PivPinOnlyMode.None) == false) { throw new OperationCanceledException( @@ -1216,11 +1233,9 @@ public bool TryResetPin(ReadOnlyMemory puk, ReadOnlyMemory newPin, o // The delegate is a callback will perform the appropriate // Command/Response operations (Change or Reset). // If the mode is not None, then set the YubiKey to that mode. - private bool TryChangeReference( - KeyEntryRequest request, - Func CommandResponse, - PivPinOnlyMode mode - ) + private bool TryChangeReference(KeyEntryRequest request, + Func CommandResponse, + PivPinOnlyMode mode) { if (KeyCollector is null) { @@ -1237,7 +1252,7 @@ PivPinOnlyMode mode try { - while (KeyCollector(keyEntryData) == true) + while (KeyCollector(keyEntryData)) { ResponseStatus status = CommandResponse(keyEntryData); @@ -1247,6 +1262,7 @@ PivPinOnlyMode mode { SetPinOnlyMode(keyEntryData.GetNewValue(), mode, out _); } + if (request == KeyEntryRequest.ChangePivPin) { UpdateAdminData(); @@ -1282,6 +1298,7 @@ PivPinOnlyMode mode private ResponseStatus ChangePinOrPuk(KeyEntryData keyEntryData) { byte slotNumber = PivSlot.Puk; + if (keyEntryData.Request == KeyEntryRequest.ChangePivPin) { slotNumber = PivSlot.Pin; @@ -1289,6 +1306,7 @@ private ResponseStatus ChangePinOrPuk(KeyEntryData keyEntryData) var changeCommand = new ChangeReferenceDataCommand( slotNumber, keyEntryData.GetCurrentValue(), keyEntryData.GetNewValue()); + ChangeReferenceDataResponse changeResponse = Connection.SendCommand(changeCommand); // If success, GetData returns null. @@ -1305,6 +1323,7 @@ private ResponseStatus ResetPin(KeyEntryData keyEntryData) { var resetCommand = new ResetRetryCommand( keyEntryData.GetCurrentValue(), keyEntryData.GetNewValue()); + ResetRetryResponse resetResponse = Connection.SendCommand(resetCommand); // If success, GetData returns null. @@ -1333,13 +1352,15 @@ private void UpdateAdminData() if (ManagementKeyAuthenticated) { bool isValid = TryReadObject(out AdminData adminData); + using (adminData) { if (!isValid || adminData.IsEmpty) { return; } - if (!adminData.PinProtected && (adminData.Salt is null)) + + if (!adminData.PinProtected && adminData.Salt is null) { return; } diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.Pinonly.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.Pinonly.cs index 78d14a52..32d43fc8 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.Pinonly.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.Pinonly.cs @@ -16,10 +16,10 @@ using System.Globalization; using System.Security; using System.Security.Cryptography; +using Yubico.Core.Logging; +using Yubico.YubiKey.Cryptography; using Yubico.YubiKey.Piv.Commands; using Yubico.YubiKey.Piv.Objects; -using Yubico.YubiKey.Cryptography; -using Yubico.Core.Logging; namespace Yubico.YubiKey.Piv { @@ -89,13 +89,16 @@ public PivPinOnlyMode GetPinOnlyMode() _log.LogInformation("Get the PIV PIN-only mode of a YubiKey based on AdminData."); PivPinOnlyMode returnValue = PivPinOnlyMode.PinProtectedUnavailable | PivPinOnlyMode.PinDerivedUnavailable; + if (TryReadObject(out AdminData adminData)) { returnValue = PivPinOnlyMode.None; + if (adminData.PinProtected) { returnValue |= PivPinOnlyMode.PinProtected; } + if (!(adminData.Salt is null)) { returnValue |= PivPinOnlyMode.PinDerived; @@ -211,11 +214,13 @@ public PivPinOnlyMode TryRecoverPinOnlyMode() // to set the PukBlocked field in adminData to true, so make sure // it is indeed true. _ = BlockPinOrPuk(PivSlot.Puk); + using var adminData = new AdminData { PukBlocked = true, PinProtected = true }; + WriteObject(adminData); return PivPinOnlyMode.PinProtected; @@ -240,6 +245,7 @@ public PivPinOnlyMode TryRecoverPinOnlyMode() WriteObject(pinProtect); PivPinOnlyMode protectMode = PivPinOnlyMode.None; + if (adminData.PinProtected) { SetPinOnlyMode(PivPinOnlyMode.PinProtected, ManagementKeyAlgorithm); @@ -273,12 +279,15 @@ public PivPinOnlyMode TryRecoverPinOnlyMode() // "correct, we want to leave it as is, except make sure the // PinProtected property is false and the Salt is null. // If that bit is set, then we want to clear ADMIN DATA. - using AdminData adminData = returnValue.HasFlag(PivPinOnlyMode.PinDerivedUnavailable) ? - new AdminData() : ReadObject(); + using AdminData adminData = returnValue.HasFlag(PivPinOnlyMode.PinDerivedUnavailable) + ? new AdminData() + : ReadObject(); + if (!adminData.IsEmpty) { adminData.PinProtected = false; } + adminData.SetSalt(ReadOnlyMemory.Empty); WriteObject(adminData); @@ -331,6 +340,7 @@ private PivPinOnlyMode TryAuthenticatePinOnly(bool trustAdminData) bool tryPinDerived = true; PivPinOnlyMode returnValue = PivPinOnlyMode.None; + if (trustAdminData) { returnValue = GetPinOnlyMode(); @@ -345,6 +355,7 @@ private PivPinOnlyMode TryAuthenticatePinOnly(bool trustAdminData) try { KeyCollector = specialKeyCollector.KeyCollectorSpecial; + if (tryPinProtected) { returnValue = GetPrintedPinProtectedStatus(specialKeyCollector, UserKeyCollector); @@ -358,8 +369,10 @@ private PivPinOnlyMode TryAuthenticatePinOnly(bool trustAdminData) if (tryPinDerived) { using var adminData = new AdminData(); + returnValue |= GetPinDerivedStatus( - adminData, returnValue.HasFlag(PivPinOnlyMode.PinProtected), specialKeyCollector, UserKeyCollector); + adminData, returnValue.HasFlag(PivPinOnlyMode.PinProtected), specialKeyCollector, + UserKeyCollector); } return returnValue; @@ -379,9 +392,8 @@ private PivPinOnlyMode TryAuthenticatePinOnly(bool trustAdminData) // authenticates, return PinProtected. If not, return Unavailable. // If there is data but it is not PinProtectedData, the pinProtect object // will be empty and return Unavailable. - private PivPinOnlyMode GetPrintedPinProtectedStatus( - SpecialKeyCollector specialKeyCollector, - Func? UserKeyCollector) + private PivPinOnlyMode GetPrintedPinProtectedStatus(SpecialKeyCollector specialKeyCollector, + Func? UserKeyCollector) { // We could call the ReadObject method, but if the PIN is not // verified, ReadObject won't collect and save it. @@ -404,6 +416,7 @@ private PivPinOnlyMode GetPrintedPinProtectedStatus( if (getDataResponse.Status == ResponseStatus.Success) { using var pinProtect = new PinProtectedData(); + if (pinProtect.TryDecode(getDataResponse.GetData())) { if (pinProtect.ManagementKey is null) @@ -442,11 +455,10 @@ private PivPinOnlyMode GetPrintedPinProtectedStatus( // This will update the adminData object passed in with the contents of // the ADMIN DATA storage location. This method expects the adminData to // be empty. - private PivPinOnlyMode GetPinDerivedStatus( - AdminData adminData, - bool isPinProtected, - SpecialKeyCollector specialKeyCollector, - Func? UserKeyCollector) + private PivPinOnlyMode GetPinDerivedStatus(AdminData adminData, + bool isPinProtected, + SpecialKeyCollector specialKeyCollector, + Func? UserKeyCollector) { // We could use the TryReadObject to get the admin data, but that // returns a new object. We need to fill the incoming object with the @@ -471,17 +483,19 @@ private PivPinOnlyMode GetPinDerivedStatus( // 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 (MemoryExtensions.SequenceEqual( - specialKeyCollector.GetCurrentMgmtKey().Span, - specialKeyCollector.GetNewMgmtKey().Span)) + specialKeyCollector.GetCurrentMgmtKey().Span, + specialKeyCollector.GetNewMgmtKey().Span)) { return PivPinOnlyMode.PinDerived; } @@ -758,6 +772,7 @@ public void SetPinOnlyMode(PivPinOnlyMode pinOnlyMode, PivAlgorithm mgmtKeyAlgor private void SetPinOnlyMode(ReadOnlyMemory pin, PivPinOnlyMode pinOnlyMode, out int? retriesRemaining) { ReadOnlyMemory pinToUse = pin; + if (pin.Length == 0) { pinToUse = new ReadOnlyMemory(new byte[] { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36 }); @@ -769,6 +784,7 @@ private void SetPinOnlyMode(ReadOnlyMemory pin, PivPinOnlyMode pinOnlyMode try { KeyCollector = specialKeyCollector.KeyCollectorSpecial; + if (specialKeyCollector.TrySetPin(this, pinToUse, out retriesRemaining)) { SetPinOnlyMode(specialKeyCollector, UserKeyCollector, pinOnlyMode, ManagementKeyAlgorithm); @@ -786,11 +802,10 @@ private void SetPinOnlyMode(ReadOnlyMemory pin, PivPinOnlyMode pinOnlyMode // KeyCollector to obtain it. // This method assumes that the caller has set this PivSession's // KeyCollector to the special, and will reset it to the User's when done. - private void SetPinOnlyMode( - SpecialKeyCollector specialKeyCollector, - Func? UserKeyCollector, - PivPinOnlyMode pinOnlyMode, - PivAlgorithm mgmtKeyAlgorithm) + private void SetPinOnlyMode(SpecialKeyCollector specialKeyCollector, + Func? UserKeyCollector, + PivPinOnlyMode pinOnlyMode, + PivAlgorithm mgmtKeyAlgorithm) { if (pinOnlyMode.HasFlag(PivPinOnlyMode.PinProtectedUnavailable) || pinOnlyMode.HasFlag(PivPinOnlyMode.PinDerivedUnavailable)) @@ -811,7 +826,7 @@ private void SetPinOnlyMode( // If the caller wants a Mode of None, we're going to ignore the // mgmtKeyAlgorithm arg, and we're going to want to clear the // YubiKey, so say it is a new algorithm. - bool newAlgorithm = (mgmtKeyAlgorithm != ManagementKeyAlgorithm) || (pinOnlyMode == PivPinOnlyMode.None); + bool newAlgorithm = mgmtKeyAlgorithm != ManagementKeyAlgorithm || pinOnlyMode == PivPinOnlyMode.None; // We're creating this variable so that we know which mode to set. // We might need to set a mode because the caller requests it and it @@ -828,6 +843,7 @@ private void SetPinOnlyMode( newAlgorithm, ref newMode); using var adminData = new AdminData(); + if (pinOnlyCheck == PinOnlyCheck.CanContinue) { currentMode |= GetPinDerivedStatus( @@ -857,7 +873,7 @@ private void SetPinOnlyMode( // If the mgmt key has not yet been authenticated, then get it // using the KeyCollector. - if ((!currentMode.HasFlag(PivPinOnlyMode.PinProtected)) && (!currentMode.HasFlag(PivPinOnlyMode.PinDerived))) + if (!currentMode.HasFlag(PivPinOnlyMode.PinProtected) && !currentMode.HasFlag(PivPinOnlyMode.PinDerived)) { // Actually, before we do that, check to see if the requested is // None. It's possible that one or both of the modes is @@ -936,24 +952,16 @@ private void SetPinOnlyMode( } } - private enum PinOnlyCheck - { - Unavailable = 0, - Complete = 1, - CanContinue = 2, - } - // Check the currentMode against pinOnlyMode, newAlgorithm, tested, and // testedUnavailable. // Set newMode and return a value based on the results of the comparison // The tested arg is what we're testing for, PinProtected or PinDerived. - private static PinOnlyCheck CheckPinOnlyStatus( - PivPinOnlyMode currentMode, - PivPinOnlyMode pinOnlyMode, - PivPinOnlyMode tested, - PivPinOnlyMode testedUnavailable, - bool newAlgorithm, - ref PivPinOnlyMode newMode) + private static PinOnlyCheck CheckPinOnlyStatus(PivPinOnlyMode currentMode, + PivPinOnlyMode pinOnlyMode, + PivPinOnlyMode tested, + PivPinOnlyMode testedUnavailable, + bool newAlgorithm, + ref PivPinOnlyMode newMode) { // Look at PinProtected. // At this point, if the requested mode is PinProtected, and the @@ -1023,6 +1031,7 @@ private void ClearPinOnly(PivPinOnlyMode currentMode, SpecialKeyCollector specia specialKeyCollector.SetKeyData( SpecialKeyCollector.SetKeyDataDefault, ReadOnlyMemory.Empty, true, PivAlgorithm.TripleDes); + specialKeyCollector.ChangeManagementKey(this, PivAlgorithm.TripleDes); } @@ -1032,6 +1041,7 @@ private void PutEmptyData(int dataTag) var putCmd = new PutDataCommand(dataTag, emptyObject); PutDataResponse putRsp = Connection.SendCommand(putCmd); + if (putRsp.Status != ResponseStatus.Success) { throw new InvalidOperationException(putRsp.StatusMessage); @@ -1048,13 +1058,12 @@ private void PutEmptyData(int dataTag) // PIN-protected. If that's the case, authMode will be set to // PinProtected. Set the ref arg setPinProtected to true in this case. // Otherwise, leave that arg alone. - private void SetYubiKeyPinDerived( - AdminData adminData, - PivPinOnlyMode currentMode, - PivAlgorithm mgmtKeyAlgorithm, - SpecialKeyCollector specialKeyCollector, - Func? UserKeyCollector, - ref PivPinOnlyMode newMode) + private void SetYubiKeyPinDerived(AdminData adminData, + PivPinOnlyMode currentMode, + PivAlgorithm mgmtKeyAlgorithm, + SpecialKeyCollector specialKeyCollector, + Func? UserKeyCollector, + ref PivPinOnlyMode newMode) { // We need the actual PIN in order to derive the mgmt key, so even if // the PIN has already been verified, collect it. @@ -1090,15 +1099,15 @@ private void SetYubiKeyPinDerived( // If the current key in specialKeyCollector is not the default, use that // key data. That data is either the "pre-existing" mgmt key data, or it // is the PIN-derived data. - private void SetYubiKeyPinProtected( - AdminData adminData, - PivAlgorithm mgmtKeyAlgorithm, - SpecialKeyCollector specialKeyCollector) + private void SetYubiKeyPinProtected(AdminData adminData, + PivAlgorithm mgmtKeyAlgorithm, + SpecialKeyCollector specialKeyCollector) { if (specialKeyCollector.IsCurrentKeyDefault()) { specialKeyCollector.SetKeyData( SpecialKeyCollector.SetKeyDataRandom, ReadOnlyMemory.Empty, true, mgmtKeyAlgorithm); + specialKeyCollector.ChangeManagementKey(this, mgmtKeyAlgorithm); } @@ -1132,8 +1141,7 @@ private void SetYubiKeyPinProtected( // really is not PIN-derived. // The only way to get a false return is if the PIN does not verify, and // even then, only if the ADMIN DATA says the mgmt key is PinDerived. - private bool TryGetChangePinMode( - ReadOnlyMemorypin, out PivPinOnlyMode mode, out int? retriesRemaining) + private bool TryGetChangePinMode(ReadOnlyMemory pin, out PivPinOnlyMode mode, out int? retriesRemaining) { retriesRemaining = null; @@ -1146,7 +1154,7 @@ private bool TryGetChangePinMode( try { - if (!isValid || (adminData.Salt is null)) + if (!isValid || adminData.Salt is null) { return true; } @@ -1168,16 +1176,17 @@ private bool TryGetChangePinMode( var salt = (ReadOnlyMemory)adminData.Salt; _ = specialKeyCollector.DeriveKeyData(salt, ManagementKeyAlgorithm, false); + specialKeyCollector.SetKeyData( SpecialKeyCollector.SetKeyDataDefault, ReadOnlyMemory.Empty, true, PivAlgorithm.TripleDes); // If this fails, then the mgmt key is not PIN-derived from the // PIN and salt, so we'll say it is not PIN-derived. if (!TryForcedChangeManagementKey( - specialKeyCollector.GetCurrentMgmtKey(), - specialKeyCollector.GetNewMgmtKey(), - PivTouchPolicy.Never, - PivAlgorithm.TripleDes)) + specialKeyCollector.GetCurrentMgmtKey(), + specialKeyCollector.GetNewMgmtKey(), + PivTouchPolicy.Never, + PivAlgorithm.TripleDes)) { return true; } @@ -1190,14 +1199,16 @@ private bool TryGetChangePinMode( // If there is data in PRINTED, and it contains the same mgmt key // that was derived from the PIN and Salt, then yes. isValid = TryReadObject(out PinProtectedData pinProtect); + using (pinProtect) { - if (isValid && (!(pinProtect.ManagementKey is null))) + if (isValid && !(pinProtect.ManagementKey is null)) { var mgmtKey = (ReadOnlyMemory)pinProtect.ManagementKey; + if (MemoryExtensions.SequenceEqual( - specialKeyCollector.GetCurrentMgmtKey().Span, - mgmtKey.Span)) + specialKeyCollector.GetCurrentMgmtKey().Span, + mgmtKey.Span)) { mode |= PivPinOnlyMode.PinProtected; } @@ -1224,12 +1235,16 @@ private bool TryGetChangePinMode( return true; } + private enum PinOnlyCheck + { + Unavailable = 0, + Complete = 1, + CanContinue = 2, + } + // This class keeps track of the key data and its length. private sealed class MgmtKeyHolder : IDisposable { - // This property will be the key data, of the appropriate length. - public Memory KeyData { get; private set; } - private const int PinDerivedSaltLength = 16; private const int MaxKeyLength = 32; private readonly byte[] _keyBuffer = new byte[MaxKeyLength]; @@ -1245,6 +1260,20 @@ public MgmtKeyHolder() _disposed = false; } + // This property will be the key data, of the appropriate length. + public Memory KeyData { get; private set; } + + public void Dispose() + { + if (_disposed) + { + return; + } + + CryptographicOperations.ZeroMemory(_keyData.Span); + _disposed = true; + } + // Copy the newData into the local buffer. // Set the KeyData property to the actual key data. That is, if the // newData is smaller than the internal buffer, then KeyData will be @@ -1271,7 +1300,8 @@ public void SetKeyData(ReadOnlyMemory newData, PivAlgorithm algorithm) do { randomObject.GetBytes(_keyBuffer, 0, newLength); - } while (IsKeyDataWeak(algorithm)); + } + while (IsKeyDataWeak(algorithm)); } KeyData = _keyData.Slice(0, newLength); @@ -1282,8 +1312,8 @@ public void SetKeyData(ReadOnlyMemory newData, PivAlgorithm algorithm) // Return the salt. // It is the responsibility of the caller to make sure the pin is the // correct length. - public ReadOnlyMemory DeriveKeyData( - ReadOnlyMemory pin, ReadOnlyMemory salt, PivAlgorithm algorithm) + public ReadOnlyMemory DeriveKeyData(ReadOnlyMemory pin, ReadOnlyMemory salt, + PivAlgorithm algorithm) { ReadOnlyMemory returnValue = salt; @@ -1297,7 +1327,8 @@ public ReadOnlyMemory DeriveKeyData( { randomObject.GetBytes(saltData, 0, PinDerivedSaltLength); PerformKeyDerive(pin, saltData, algorithm); - } while (IsKeyDataWeak(algorithm)); + } + while (IsKeyDataWeak(algorithm)); } else { @@ -1321,6 +1352,7 @@ public void PerformKeyDerive(ReadOnlyMemory pin, byte[] saltData, PivAlgor byte[] result = Array.Empty(); byte[] pinData = pin.ToArray(); + try { // This will use PBKDF2, with the PRF of HMAC with SHA-1. @@ -1356,17 +1388,6 @@ public bool IsKeyDataWeak(PivAlgorithm algorithm) return false; } - - public void Dispose() - { - if (_disposed) - { - return; - } - - CryptographicOperations.ZeroMemory(_keyData.Span); - _disposed = true; - } } private sealed class SpecialKeyCollector : IDisposable @@ -1374,26 +1395,26 @@ private sealed class SpecialKeyCollector : IDisposable public const int SetKeyDataBuffer = 1; public const int SetKeyDataRandom = 2; public const int SetKeyDataDefault = 4; - private readonly Memory _defaultKey; - private readonly MgmtKeyHolder _currentKey; - private readonly MgmtKeyHolder _newKey; private const int MaxPinLength = 8; - private int _pinLength; - private readonly Memory _pinMemory; + private readonly MgmtKeyHolder _currentKey; + private readonly Memory _defaultKey; + private readonly MgmtKeyHolder _newKey; private readonly byte[] _pinData = new byte[MaxPinLength]; + private readonly Memory _pinMemory; private bool _disposed; - - public bool PinCollected { get; private set; } + private int _pinLength; public SpecialKeyCollector() { - _defaultKey = new Memory(new byte[] { + _defaultKey = new Memory(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 }); + _currentKey = new MgmtKeyHolder(); _newKey = new MgmtKeyHolder(); @@ -1407,6 +1428,28 @@ public SpecialKeyCollector() _disposed = false; } + public bool PinCollected { get; private set; } + + // Note that .NET recommends a Dispose method call Dispose(true) and + // GC.SuppressFinalize(this). The actual disposal is in the + // Dispose(bool) method. + // + // However, that does not apply to sealed classes. + // So the Dispose method will simply perform the + // "closing" process, no call to Dispose(bool) or GC. + public void Dispose() + { + if (_disposed) + { + return; + } + + _currentKey.Dispose(); + _newKey.Dispose(); + CryptographicOperations.ZeroMemory(_pinMemory.Span); + _disposed = true; + } + // Check to see if the data is the default mgmt key. public bool IsCurrentKeyDefault() => MemoryExtensions.SequenceEqual(_defaultKey.Span, _currentKey.KeyData.Span); @@ -1435,12 +1478,14 @@ public void SetKeyData(int setFlag, ReadOnlyMemory keyData, bool isNewKey, if (setFlag == SetKeyDataBuffer) { dest.SetKeyData(keyData, algorithm); + return; } if (setFlag == SetKeyDataRandom) { dest.SetKeyData(ReadOnlyMemory.Empty, algorithm); + return; } @@ -1462,8 +1507,7 @@ public void SetKeyData(int setFlag, ReadOnlyMemory keyData, bool isNewKey, // will generate a new salt and try again. // But this method will generate whatever key (weak or not) is the // result if a salt is given. - public ReadOnlyMemory DeriveKeyData( - ReadOnlyMemory salt, PivAlgorithm algorithm, bool isNewKey) + public ReadOnlyMemory DeriveKeyData(ReadOnlyMemory salt, PivAlgorithm algorithm, bool isNewKey) { MgmtKeyHolder dest = isNewKey ? _newKey : _currentKey; @@ -1494,9 +1538,8 @@ public void ChangeManagementKey(PivSession pivSession, PivAlgorithm algorithm) // exception. // Upon completion of this method, the correct mgmt key is in the current // key. - public void AuthMgmtKeyAndSave( - PivSession pivSession, - Func? UserKeyCollector) + public void AuthMgmtKeyAndSave(PivSession pivSession, + Func? UserKeyCollector) { // First, try the default key. If it works, we're done. // If we reach this point, the special key collector has just been @@ -1523,9 +1566,11 @@ public void AuthMgmtKeyAndSave( try { - while (UserKeyCollector(keyEntryData) == true) + while (UserKeyCollector(keyEntryData)) { - SetKeyData(SetKeyDataBuffer, keyEntryData.GetCurrentValue(), false, pivSession.ManagementKeyAlgorithm); + SetKeyData(SetKeyDataBuffer, keyEntryData.GetCurrentValue(), false, + pivSession.ManagementKeyAlgorithm); + if (pivSession.TryAuthenticateWithKeyCollector(true)) { return; @@ -1560,9 +1605,8 @@ public void AuthMgmtKeyAndSave( // property. // If the If the user cancels (the UserKeyCollector returns false), // this method will throw an exception. - public void VerifyPinAndSave( - PivSession pivSession, - Func? UserKeyCollector) + public void VerifyPinAndSave(PivSession pivSession, + Func? UserKeyCollector) { if (!TryVerifyPinAndSave(pivSession, UserKeyCollector, out _)) { @@ -1576,10 +1620,9 @@ public void VerifyPinAndSave( // Verify the PIN and save it in this. // If the user cancels, return false. - public bool TryVerifyPinAndSave( - PivSession pivSession, - Func? UserKeyCollector, - out int? retriesRemaining) + public bool TryVerifyPinAndSave(PivSession pivSession, + Func? UserKeyCollector, + out int? retriesRemaining) { retriesRemaining = null; @@ -1603,7 +1646,7 @@ public bool TryVerifyPinAndSave( try { - while (UserKeyCollector(keyEntryData) == true) + while (UserKeyCollector(keyEntryData)) { if (TrySetPin(pivSession, keyEntryData.GetCurrentValue(), out retriesRemaining)) { @@ -1646,7 +1689,7 @@ public bool KeyCollectorSpecial(KeyEntryData keyEntryData) return false; } - if (keyEntryData.IsRetry == true) + if (keyEntryData.IsRetry) { return false; } @@ -1661,36 +1704,19 @@ public bool KeyCollectorSpecial(KeyEntryData keyEntryData) case KeyEntryRequest.AuthenticatePivManagementKey: keyEntryData.SubmitValue(_currentKey.KeyData.Span); + return true; case KeyEntryRequest.ChangePivManagementKey: keyEntryData.SubmitValues(_currentKey.KeyData.Span, _newKey.KeyData.Span); + return true; case KeyEntryRequest.VerifyPivPin: keyEntryData.SubmitValue(_pinMemory.Slice(0, _pinLength).Span); - return true; - } - } - // Note that .NET recommends a Dispose method call Dispose(true) and - // GC.SuppressFinalize(this). The actual disposal is in the - // Dispose(bool) method. - // - // However, that does not apply to sealed classes. - // So the Dispose method will simply perform the - // "closing" process, no call to Dispose(bool) or GC. - public void Dispose() - { - if (_disposed) - { - return; + return true; } - - _currentKey.Dispose(); - _newKey.Dispose(); - CryptographicOperations.ZeroMemory(_pinMemory.Span); - _disposed = true; } } } diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.cs index 6ee0eff2..ebb62292 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.cs @@ -13,13 +13,13 @@ // limitations under the License. using System; -using System.Security; using System.Globalization; -using Yubico.YubiKey.Piv.Commands; +using System.Security; +using Yubico.Core.Logging; using Yubico.YubiKey.Cryptography; -using Yubico.YubiKey.Scp03; using Yubico.YubiKey.InterIndustry.Commands; -using Yubico.Core.Logging; +using Yubico.YubiKey.Piv.Commands; +using Yubico.YubiKey.Scp03; namespace Yubico.YubiKey.Piv { @@ -143,39 +143,9 @@ namespace Yubico.YubiKey.Piv /// public sealed partial class PivSession : IDisposable { - private bool _disposed; private readonly Logger _log = Log.GetLogger(); private readonly IYubiKeyDevice _yubiKeyDevice; - - /// - /// The object that represents the connection to the YubiKey. Most - /// applications will ignore this, but it can be used to call Commands - /// directly. - /// - public IYubiKeyConnection Connection { get; private set; } - - /// - /// The Delegate this class will call when it needs a PIN, PUK, or - /// management key. - /// - /// - /// The delegate provided will read the KeyEntryData which - /// contains the information needed to determine what to collect and - /// methods to submit what was collected. The delegate will return - /// true for success or false for "cancel". A cancel will - /// usually happen when the user has clicked a "Cancel" button. That is - /// often the case when the user has entered the wrong value a number of - /// times, the remaining tries count is getting low, and they would like - /// to stop trying before the YubiKey is blocked. - /// - /// Note that the SDK will call the KeyCollector with a - /// Request of Release when the process completes. In this - /// case, the KeyCollector MUST NOT throw an exception. The - /// Release is called from inside a finally block, and it - /// is a bad idea to throw exceptions from inside finally. - /// - /// - public Func? KeyCollector { get; set; } + private bool _disposed; // The default constructor explicitly defined. We don't want it to be // used. @@ -253,16 +223,20 @@ public PivSession(IYubiKeyDevice yubiKey, StaticKeys scp03Keys) private PivSession(StaticKeys? scp03Keys, IYubiKeyDevice yubiKey) { _log.LogInformation("Create a new instance of PivSession" + (scp03Keys is null ? "." : " over SCP03")); + if (yubiKey is null) { throw new ArgumentNullException(nameof(yubiKey)); } - Connection = scp03Keys is null ? - yubiKey.Connect(YubiKeyApplication.Piv) : yubiKey.ConnectScp03(YubiKeyApplication.Piv, scp03Keys); + Connection = scp03Keys is null + ? yubiKey.Connect(YubiKeyApplication.Piv) + : yubiKey.ConnectScp03(YubiKeyApplication.Piv, scp03Keys); + ResetAuthenticationStatus(); ManagementKeyAlgorithm = PivAlgorithm.TripleDes; + if (yubiKey.HasFeature(YubiKeyFeature.PivAesManagementKey)) { var getMetadataCmd = new GetMetadataCommand(PivSlot.Management); @@ -279,6 +253,68 @@ private PivSession(StaticKeys? scp03Keys, IYubiKeyDevice yubiKey) _disposed = false; } + /// + /// The object that represents the connection to the YubiKey. Most + /// applications will ignore this, but it can be used to call Commands + /// directly. + /// + public IYubiKeyConnection Connection { get; private set; } + + /// + /// The Delegate this class will call when it needs a PIN, PUK, or + /// management key. + /// + /// + /// The delegate provided will read the KeyEntryData which + /// contains the information needed to determine what to collect and + /// methods to submit what was collected. The delegate will return + /// true for success or false for "cancel". A cancel will + /// usually happen when the user has clicked a "Cancel" button. That is + /// often the case when the user has entered the wrong value a number of + /// times, the remaining tries count is getting low, and they would like + /// to stop trying before the YubiKey is blocked. + /// + /// Note that the SDK will call the KeyCollector with a + /// Request of Release when the process completes. In this + /// case, the KeyCollector MUST NOT throw an exception. The + /// Release is called from inside a finally block, and it + /// is a bad idea to throw exceptions from inside finally. + /// + /// + public Func? KeyCollector { get; set; } + + /// + /// When the PivSession object goes out of scope, this method is called. + /// It will close the session. The most important function of closing a + /// session is to "un-authenticate" the management key and "un-verify" + /// the PIN. + /// + + // Note that .NET recommends a Dispose method call Dispose(true) and + // GC.SuppressFinalize(this). The actual disposal is in the + // Dispose(bool) method. + // + // However, that does not apply to sealed classes. + // So the Dispose method will simply perform the + // "closing" process, no call to Dispose(bool) or GC. + public void Dispose() + { + if (_disposed) + { + return; + } + + // At the moment, there is no "close session" method. So for now, + // just connect to the management application. + _ = Connection.SendCommand(new SelectApplicationCommand(YubiKeyApplication.Management)); + KeyCollector = null; + ResetAuthenticationStatus(); + + Connection.Dispose(); + + _disposed = true; + } + // Reset any fields and properties related to authentication or // verification to the initial state: not authenticated, verified, etc. private void ResetAuthenticationStatus() @@ -333,6 +369,7 @@ private void ResetAuthenticationStatus() public PivMetadata GetMetadata(byte slotNumber) { _log.LogInformation("GetMetadata for slot number {0:X2}.", slotNumber); + if (_yubiKeyDevice.HasFeature(YubiKeyFeature.PivMetadata)) { var metadataCommand = new GetMetadataCommand(slotNumber); @@ -388,10 +425,11 @@ public PivMetadata GetMetadata(byte slotNumber) public void ResetApplication() { _log.LogInformation("Reset the PIV application."); + // To reset, both the PIN and PUK must be blocked. - if (BlockPinOrPuk(PivSlot.Pin) == true) + if (BlockPinOrPuk(PivSlot.Pin)) { - if (BlockPinOrPuk(PivSlot.Puk) == true) + if (BlockPinOrPuk(PivSlot.Puk)) { var resetCommand = new ResetPivCommand(); ResetPivResponse resetResponse = Connection.SendCommand(resetCommand); @@ -399,6 +437,7 @@ public void ResetApplication() if (resetResponse.Status == ResponseStatus.Success) { ResetAuthenticationStatus(); + return; } } @@ -425,14 +464,19 @@ private bool BlockPinOrPuk(byte slotNumber) { _log.LogInformation($"Block the {(slotNumber == 0x80 ? "PIN" : "PUK")}."); int retriesRemaining; + do { - byte[] currentValue = new byte[] { + byte[] currentValue = new byte[] + { 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01 }; - byte[] newValue = new byte[] { + + byte[] newValue = new byte[] + { 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22 }; + var changeCommand = new ChangeReferenceDataCommand(slotNumber, currentValue, newValue); ChangeReferenceDataResponse changeResponse = Connection.SendCommand(changeCommand); @@ -442,41 +486,10 @@ private bool BlockPinOrPuk(byte slotNumber) } retriesRemaining = changeResponse.GetData() ?? 1; - - } while (retriesRemaining > 0); - - return true; - } - - /// - /// When the PivSession object goes out of scope, this method is called. - /// It will close the session. The most important function of closing a - /// session is to "un-authenticate" the management key and "un-verify" - /// the PIN. - /// - // Note that .NET recommends a Dispose method call Dispose(true) and - // GC.SuppressFinalize(this). The actual disposal is in the - // Dispose(bool) method. - // - // However, that does not apply to sealed classes. - // So the Dispose method will simply perform the - // "closing" process, no call to Dispose(bool) or GC. - public void Dispose() - { - if (_disposed) - { - return; } + while (retriesRemaining > 0); - // At the moment, there is no "close session" method. So for now, - // just connect to the management application. - _ = Connection.SendCommand(new SelectApplicationCommand(YubiKeyApplication.Management)); - KeyCollector = null; - ResetAuthenticationStatus(); - - Connection.Dispose(); - - _disposed = true; + return true; } } } diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSlot.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSlot.cs index 1ce6850d..24d7e0e8 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSlot.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSlot.cs @@ -329,9 +329,9 @@ public static bool IsValidSlotNumber(byte slotNumber) // something that is only dependent on some private const values, but // the slots are almost certainly never going to change. If they do // change, this code will need to be revisited. - return (((slotNumber >= Pin) && (slotNumber <= Retired20)) - || ((slotNumber >= Authentication) && (slotNumber <= CardAuthentication)) - || (slotNumber == Attestation)); + return (slotNumber >= Pin && slotNumber <= Retired20) + || (slotNumber >= Authentication && slotNumber <= CardAuthentication) + || slotNumber == Attestation; } /// @@ -370,10 +370,10 @@ public static bool IsValidSlotNumber(byte slotNumber) /// public static bool IsValidSlotNumberForGenerate(byte slotNumber) { - return ((slotNumber != Management) - && (((slotNumber >= Retired1) && (slotNumber <= Retired20)) - || ((slotNumber >= Authentication) && (slotNumber <= CardAuthentication)) - || (slotNumber == Attestation))); + return slotNumber != Management + && ((slotNumber >= Retired1 && slotNumber <= Retired20) + || (slotNumber >= Authentication && slotNumber <= CardAuthentication) + || slotNumber == Attestation); } /// @@ -415,9 +415,9 @@ public static bool IsValidSlotNumberForSigning(byte slotNumber) // something that is only dependent on some private const values, but // the slots are almost certainly never going to change. If they do // change, this code will need to be revisited. - return ((slotNumber != Management) - && (((slotNumber >= Retired1) && (slotNumber <= Retired20)) - || ((slotNumber >= Authentication) && (slotNumber <= CardAuthentication)))); + return slotNumber != Management + && ((slotNumber >= Retired1 && slotNumber <= Retired20) + || (slotNumber >= Authentication && slotNumber <= CardAuthentication)); } } } diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Scp03/ChannelMac.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Scp03/ChannelMac.cs index ca454c04..975f27ce 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Scp03/ChannelMac.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Scp03/ChannelMac.cs @@ -16,9 +16,9 @@ using System.IO; using System.Linq; using System.Security.Cryptography; -using Yubico.YubiKey.Cryptography; -using Yubico.Core.Iso7816; using Yubico.Core.Cryptography; +using Yubico.Core.Iso7816; +using Yubico.YubiKey.Cryptography; namespace Yubico.YubiKey.Scp03 { diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Scp03/Commands/PutKeyResponse.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Scp03/Commands/PutKeyResponse.cs index f8d4f696..00b3b224 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Scp03/Commands/PutKeyResponse.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Scp03/Commands/PutKeyResponse.cs @@ -22,7 +22,7 @@ namespace Yubico.YubiKey.Scp03.Commands /// internal class PutKeyResponse : Scp03Response, IYubiKeyResponseWithData> { - private byte[] _checksum; + private readonly byte[] _checksum; public PutKeyResponse(ResponseApdu responseApdu) : base(responseApdu) diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Scp03/Commands/Scp03Response.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Scp03/Commands/Scp03Response.cs index 4f160ed4..e6073e18 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Scp03/Commands/Scp03Response.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Scp03/Commands/Scp03Response.cs @@ -40,7 +40,7 @@ public virtual void ThrowIfFailed() Debug.Assert(Status == ResponseStatus.Success); return; default: - throw new Exception(); + throw new Exception(); } } } diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Scp03/Derivation.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Scp03/Derivation.cs index 276592e6..d14cda86 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Scp03/Derivation.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Scp03/Derivation.cs @@ -14,8 +14,8 @@ using System; using System.Security.Cryptography; -using Yubico.PlatformInterop; using Yubico.Core.Cryptography; +using Yubico.PlatformInterop; using Yubico.YubiKey.Cryptography; namespace Yubico.YubiKey.Scp03 @@ -40,11 +40,11 @@ public static byte[] Derive( byte[] hostChallenge, byte[] cardChallenge) { - if ((outputLenBits != 0x40) && (outputLenBits != 0x80)) + if (outputLenBits != 0x40 && outputLenBits != 0x80) { throw new SecureChannelException(ExceptionMessages.IncorrectDerivationLength); } - if ((hostChallenge.Length != 8) || (cardChallenge.Length != 8)) + if (hostChallenge.Length != 8 || cardChallenge.Length != 8) { throw new SecureChannelException(ExceptionMessages.InvalidChallengeLength); } diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Scp03/Scp03CcidConnection.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Scp03/Scp03CcidConnection.cs index 61b7e649..fbb352bf 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Scp03/Scp03CcidConnection.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Scp03/Scp03CcidConnection.cs @@ -13,10 +13,10 @@ // limitations under the License. using System; +using System.Linq; +using Yubico.Core.Devices.SmartCard; using Yubico.YubiKey.Pipelines; using Yubico.YubiKey.Scp03; -using Yubico.Core.Devices.SmartCard; -using System.Linq; namespace Yubico.YubiKey { diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Scp03/Scp03Session.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Scp03/Scp03Session.cs index a1ec3bff..50f8c5b4 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Scp03/Scp03Session.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Scp03/Scp03Session.cs @@ -15,8 +15,8 @@ using System; using System.Globalization; using System.Security.Cryptography; -using Yubico.YubiKey.Scp03.Commands; using Yubico.Core.Logging; +using Yubico.YubiKey.Scp03.Commands; namespace Yubico.YubiKey.Scp03 { diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Scp03/Session.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Scp03/Session.cs index 88088b81..24647697 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Scp03/Session.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Scp03/Session.cs @@ -15,8 +15,8 @@ using System; using System.Linq; using System.Security.Cryptography; -using Yubico.YubiKey.Scp03.Commands; using Yubico.Core.Iso7816; +using Yubico.YubiKey.Scp03.Commands; namespace Yubico.YubiKey.Scp03 { diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Scp03/StaticKeys.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Scp03/StaticKeys.cs index 7e6fd70d..5f4f9cbe 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Scp03/StaticKeys.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Scp03/StaticKeys.cs @@ -86,7 +86,7 @@ public byte KeyVersionNumber set { - if ((value != DefaultKvnValue) && ((value < MinimumKvnValue) || (value > MaximumKvnValue))) + if (value != DefaultKvnValue && (value < MinimumKvnValue || value > MaximumKvnValue)) { throw new ArgumentException(ExceptionMessages.InvalidScp03Kvn); } @@ -201,7 +201,7 @@ public bool AreKeysSame(StaticKeys compareKeys) && ChannelMacKey.Span.SequenceEqual(compareKeys.ChannelMacKey.Span) && DataEncryptionKey.Span.SequenceEqual(compareKeys.DataEncryptionKey.Span)) { - return true; + return true; } } diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/SmartCardDeviceInfoFactory.cs b/Yubico.YubiKey/src/Yubico/YubiKey/SmartCardDeviceInfoFactory.cs index 2d372397..0461cce9 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/SmartCardDeviceInfoFactory.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/SmartCardDeviceInfoFactory.cs @@ -12,11 +12,11 @@ // See the License for the specific language governing permissions and // limitations under the License. -using Yubico.Core.Devices.SmartCard; -using Yubico.YubiKey.DeviceExtensions; -using System.Diagnostics.CodeAnalysis; using System; +using System.Diagnostics.CodeAnalysis; +using Yubico.Core.Devices.SmartCard; using Yubico.Core.Logging; +using Yubico.YubiKey.DeviceExtensions; namespace Yubico.YubiKey { diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/TouchFingerprintTask.cs b/Yubico.YubiKey/src/Yubico/YubiKey/TouchFingerprintTask.cs index 21e3a0fc..b683d860 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/TouchFingerprintTask.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/TouchFingerprintTask.cs @@ -134,7 +134,7 @@ public bool IsCanceled(byte commandByte) { if (commandByte == _commandByte) { - if(_notifyTask.Status == TaskStatus.Created) + if (_notifyTask.Status == TaskStatus.Created) { _notifyTask.Start(); } @@ -154,10 +154,10 @@ public bool IsCanceled(byte commandByte) // Any other value entered will be considered Release. public void SdkUpdate(KeyEntryData keyEntryData) { - KeyEntryRequest request = (keyEntryData.Request == KeyEntryRequest.EnrollFingerprint) + KeyEntryRequest request = keyEntryData.Request == KeyEntryRequest.EnrollFingerprint ? KeyEntryRequest.EnrollFingerprint : KeyEntryRequest.Release; - lock(_updateLock) + lock (_updateLock) { _isSdkUpdate = true; _keyEntryData = new KeyEntryData(UserCancel) @@ -169,7 +169,7 @@ public void SdkUpdate(KeyEntryData keyEntryData) }; } - if ((request == KeyEntryRequest.Release) && !(_connection is null)) + if (request == KeyEntryRequest.Release && !(_connection is null)) { _ = _connection.LoadQueryCancel(null); } @@ -184,7 +184,7 @@ private void RunKeyCollectorTask(Func keyCollector) KeyEntryData keyEntryData; do { - lock(_updateLock) + lock (_updateLock) { makeCall = _isSdkUpdate; keyEntryData = _keyEntryData; diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/U2f/AuthenticationData.cs b/Yubico.YubiKey/src/Yubico/YubiKey/U2f/AuthenticationData.cs index 0561e930..c0ea4a60 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/U2f/AuthenticationData.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/U2f/AuthenticationData.cs @@ -15,8 +15,8 @@ using System; using System.Buffers.Binary; using System.Globalization; -using Yubico.YubiKey.Cryptography; using Yubico.Core.Logging; +using Yubico.YubiKey.Cryptography; namespace Yubico.YubiKey.U2f { @@ -77,8 +77,8 @@ public AuthenticationData(ReadOnlyMemory encodedResponse) : base(PayloadLength, AppIdOffset, ClientDataOffset, SignatureOffset) { _log.LogInformation("Create a new instance of U2F AuthenticationData by decoding."); - if ((encodedResponse.Length < MinEncodedLength) - || ((encodedResponse.Span[MsgUserPresenceOffset] & ~UserPresenceMask) != 0)) + if (encodedResponse.Length < MinEncodedLength + || (encodedResponse.Span[MsgUserPresenceOffset] & ~UserPresenceMask) != 0) { throw new ArgumentException( string.Format( diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/U2f/Commands/SetDeviceInfoCommand.cs b/Yubico.YubiKey/src/Yubico/YubiKey/U2f/Commands/SetDeviceInfoCommand.cs index f13d3bbf..bb499c4f 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/U2f/Commands/SetDeviceInfoCommand.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/U2f/Commands/SetDeviceInfoCommand.cs @@ -12,8 +12,8 @@ // See the License for the specific language governing permissions and // limitations under the License. -using Yubico.YubiKey.Management.Commands; using Yubico.Core.Iso7816; +using Yubico.YubiKey.Management.Commands; namespace Yubico.YubiKey.U2f.Commands { diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/U2f/Commands/SetLegacyDeviceConfigCommand.cs b/Yubico.YubiKey/src/Yubico/YubiKey/U2f/Commands/SetLegacyDeviceConfigCommand.cs index ebf3ffae..49f3496d 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/U2f/Commands/SetLegacyDeviceConfigCommand.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/U2f/Commands/SetLegacyDeviceConfigCommand.cs @@ -12,8 +12,8 @@ // See the License for the specific language governing permissions and // limitations under the License. -using Yubico.YubiKey.Management.Commands; using Yubico.Core.Iso7816; +using Yubico.YubiKey.Management.Commands; namespace Yubico.YubiKey.U2f.Commands { diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/U2f/RegistrationData.cs b/Yubico.YubiKey/src/Yubico/YubiKey/U2f/RegistrationData.cs index 50edeb25..02772002 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/U2f/RegistrationData.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/U2f/RegistrationData.cs @@ -15,9 +15,9 @@ using System; using System.Globalization; using System.Security.Cryptography.X509Certificates; -using Yubico.YubiKey.Cryptography; -using Yubico.Core.Tlv; using Yubico.Core.Logging; +using Yubico.Core.Tlv; +using Yubico.YubiKey.Cryptography; namespace Yubico.YubiKey.U2f { @@ -137,9 +137,9 @@ public RegistrationData(ReadOnlyMemory encodedResponse) int certLength = 1; if (encodedResponse.Length > MinEncodedLength) { - if ((encodedResponse.Span[MsgReservedOffset] == MsgReservedValue) - && (encodedResponse.Span[MsgKeyHandleOffset] == KeyHandleLength) - && (encodedResponse.Span[MsgPublicKeyOffset] == PublicKeyTag)) + if (encodedResponse.Span[MsgReservedOffset] == MsgReservedValue + && encodedResponse.Span[MsgKeyHandleOffset] == KeyHandleLength + && encodedResponse.Span[MsgPublicKeyOffset] == PublicKeyTag) { ReadOnlyMemory certAndSig = encodedResponse.Slice(MsgCertOffset); var tlvReader = new TlvReader(certAndSig); diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/U2f/U2fHidStatus.cs b/Yubico.YubiKey/src/Yubico/YubiKey/U2f/U2fHidStatus.cs index a83c8ed7..ceceaed4 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/U2f/U2fHidStatus.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/U2f/U2fHidStatus.cs @@ -14,7 +14,7 @@ namespace Yubico.YubiKey.U2f { - internal enum U2fHidStatus + internal enum U2fHidStatus { Success = 0x00, Ctap1ErrInvalidCommand = 0x01, diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/U2f/U2fSession.Pin.cs b/Yubico.YubiKey/src/Yubico/YubiKey/U2f/U2fSession.Pin.cs index e63af261..4dc3d75a 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/U2f/U2fSession.Pin.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/U2f/U2fSession.Pin.cs @@ -16,9 +16,8 @@ using System.Globalization; using System.Security; using Yubico.Core.Iso7816; -using Yubico.YubiKey.U2f.Commands; using Yubico.Core.Logging; - +using Yubico.YubiKey.U2f.Commands; namespace Yubico.YubiKey.U2f { @@ -74,6 +73,7 @@ public sealed partial class U2fSession : IDisposable public void SetPin() { _log.LogInformation("Set the U2F PIN using the KeyCollector."); + if (TrySetPin()) { return; @@ -116,7 +116,7 @@ public bool TrySetPin() try { - while (keyCollector(keyEntryData) == true) + while (keyCollector(keyEntryData)) { if (TrySetPin(keyEntryData.GetCurrentValue())) { @@ -252,6 +252,7 @@ public bool TrySetPin(ReadOnlyMemory pin) public void ChangePin() { _log.LogInformation("Change the U2F PIN using the KeyCollector."); + if (TryChangePin()) { return; @@ -270,7 +271,7 @@ public void ChangePin() /// If the caller cancels (the return from the KeyCollector is /// false), this will return false. /// - /// + /// /// See the documentation for for more information /// on changing a PIN. /// @@ -293,7 +294,7 @@ public bool TryChangePin() try { - while (keyCollector(keyEntryData) == true) + while (keyCollector(keyEntryData)) { if (TryChangePin(keyEntryData.GetCurrentValue(), keyEntryData.GetNewValue())) { @@ -442,7 +443,7 @@ private bool CommonVerifyPin(bool throwOnCancel) try { - while (keyCollector(keyEntryData) == true) + while (keyCollector(keyEntryData)) { if (TryVerifyPin(keyEntryData.GetCurrentValue())) { diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/U2f/U2fSession.cs b/Yubico.YubiKey/src/Yubico/YubiKey/U2f/U2fSession.cs index 438022ce..0d0cb4b1 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/U2f/U2fSession.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/U2f/U2fSession.cs @@ -21,10 +21,10 @@ using System.Text; using System.Threading; using System.Threading.Tasks; -using Yubico.YubiKey.Cryptography; -using Yubico.YubiKey.U2f.Commands; using Yubico.Core.Iso7816; using Yubico.Core.Logging; +using Yubico.YubiKey.Cryptography; +using Yubico.YubiKey.U2f.Commands; namespace Yubico.YubiKey.U2f { diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/U2f/U2fSignedData.cs b/Yubico.YubiKey/src/Yubico/YubiKey/U2f/U2fSignedData.cs index 80fadf43..1b43b5ce 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/U2f/U2fSignedData.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/U2f/U2fSignedData.cs @@ -13,8 +13,8 @@ // limitations under the License. using System; -using Yubico.YubiKey.Cryptography; using Yubico.Core.Tlv; +using Yubico.YubiKey.Cryptography; namespace Yubico.YubiKey.U2f { diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/YubiHsmAuth/Commands/ListCredentialsResponse.cs b/Yubico.YubiKey/src/Yubico/YubiKey/YubiHsmAuth/Commands/ListCredentialsResponse.cs index 64d2d55b..10629995 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/YubiHsmAuth/Commands/ListCredentialsResponse.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/YubiHsmAuth/Commands/ListCredentialsResponse.cs @@ -37,7 +37,7 @@ public sealed class ListCredentialsResponse : // CryptoKeyType (1) + Touch (1) + Retry (1) + Label (min/max) private const int MinElementSize = 3 + Credential.MinLabelByteCount; private const int MaxElementSize = 3 + Credential.MaxLabelByteCount; - + /// /// Constructs a ListCredentialsResponse instance based on a ResponseApdu @@ -87,8 +87,8 @@ public List GetData() ExceptionMessages.InvalidDataTag, nextTagValue)); } - - ReadOnlySpan credentialRetryElement = + + ReadOnlySpan credentialRetryElement = tlvReader.ReadValue(DataTagConstants.LabelList).Span; // Check that it's formatted correctly diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/YubiHsmAuth/Credential.cs b/Yubico.YubiKey/src/Yubico/YubiKey/YubiHsmAuth/Credential.cs index 74603594..9340734b 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/YubiHsmAuth/Credential.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/YubiHsmAuth/Credential.cs @@ -54,7 +54,7 @@ public class Credential public CryptographicKeyType KeyType { get => _keyType; - + set { if (Enum.IsDefined(typeof(CryptographicKeyType), value) diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/YubiHsmAuth/CredentialRetryPair.cs b/Yubico.YubiKey/src/Yubico/YubiKey/YubiHsmAuth/CredentialRetryPair.cs index 38461b51..fbf53b2d 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/YubiHsmAuth/CredentialRetryPair.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/YubiHsmAuth/CredentialRetryPair.cs @@ -51,7 +51,7 @@ public class CredentialRetryPair public CredentialRetryPair(Credential credential, int retries) { Credential = credential; - + if (retries < 0) { throw new ArgumentOutOfRangeException(nameof(retries), ExceptionMessages.RetryCountNegative); diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/YubiHsmAuth/YubiHsmAuthSession.Credential.cs b/Yubico.YubiKey/src/Yubico/YubiKey/YubiHsmAuth/YubiHsmAuthSession.Credential.cs index c70304ce..93d2451d 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/YubiHsmAuth/YubiHsmAuthSession.Credential.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/YubiHsmAuth/YubiHsmAuthSession.Credential.cs @@ -16,7 +16,6 @@ using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; using System.Security; using Yubico.YubiKey.YubiHsmAuth.Commands; @@ -54,18 +53,17 @@ public partial class YubiHsmAuthSession /// /// Authentication with the management key failed. /// - public void AddCredential( - ReadOnlyMemory managementKey, - CredentialWithSecrets credentialWithSecrets) + public void AddCredential(ReadOnlyMemory managementKey, + CredentialWithSecrets credentialWithSecrets) { bool success = TryAddCredential(managementKey, credentialWithSecrets, out int? mgmtKeyRetries); if (!success) { throw new SecurityException(string.Format( - CultureInfo.CurrentCulture, - ExceptionMessages.YubiHsmAuthMgmtKeyAuthFailed, - mgmtKeyRetries)); + CultureInfo.CurrentCulture, + ExceptionMessages.YubiHsmAuthMgmtKeyAuthFailed, + mgmtKeyRetries)); } } @@ -105,16 +103,15 @@ public void AddCredential( /// Either a credential with that label /// already exists, or there is no space to add the credential. /// - public bool TryAddCredential( - ReadOnlyMemory managementKey, - CredentialWithSecrets credentialWithSecrets, - [NotNullWhen(false)] out int? managementKeyRetries - ) + public bool TryAddCredential(ReadOnlyMemory managementKey, + CredentialWithSecrets credentialWithSecrets, + [NotNullWhen(false)] out int? managementKeyRetries) { managementKeyRetries = null; AddCredentialCommand addCredCmd = new AddCredentialCommand(managementKey, credentialWithSecrets); + AddCredentialResponse addCredRsp = Connection.SendCommand(addCredCmd); if (addCredRsp.Status != ResponseStatus.Success) @@ -122,6 +119,7 @@ public bool TryAddCredential( if (addCredRsp.Status == ResponseStatus.AuthenticationRequired) { managementKeyRetries = addCredRsp.RetriesRemaining!; + return false; } else @@ -200,7 +198,7 @@ public bool TryAddCredential( /// public bool TryAddCredential(CredentialWithSecrets credentialWithSecrets) { - var keyCollector = GetKeyCollector(); + Func? keyCollector = GetKeyCollector(); var keyEntryData = new KeyEntryData() { @@ -209,7 +207,7 @@ public bool TryAddCredential(CredentialWithSecrets credentialWithSecrets) try { - while (keyCollector(keyEntryData) == true) + while (keyCollector(keyEntryData)) { bool credentialAdded = TryAddCredential( @@ -322,7 +320,7 @@ public bool TryAddCredential(CredentialWithSecrets credentialWithSecrets) /// public bool TryDeleteCredential(string label) { - var keyCollector = GetKeyCollector(); + Func? keyCollector = GetKeyCollector(); var keyEntryData = new KeyEntryData() { @@ -331,9 +329,9 @@ public bool TryDeleteCredential(string label) try { - while (keyCollector(keyEntryData) == true) + while (keyCollector(keyEntryData)) { - bool credentialDeleted = + bool credentialDeleted = TryDeleteCredential( keyEntryData.GetCurrentValue(), label, @@ -344,7 +342,7 @@ public bool TryDeleteCredential(string label) { return true; } - + // Command failed. Retry if possible, otherwise throw exception. if (managementKeyRetries.HasValue && managementKeyRetries.Value > 0) { @@ -399,18 +397,17 @@ public bool TryDeleteCredential(string label) /// /// Authentication with the management key failed. /// - public void DeleteCredential( - ReadOnlyMemory managementKey, - string label) + public void DeleteCredential(ReadOnlyMemory managementKey, + string label) { bool success = TryDeleteCredential(managementKey, label, out int? mgmtKeyRetries); if (!success) { throw new SecurityException(string.Format( - CultureInfo.CurrentCulture, - ExceptionMessages.YubiHsmAuthMgmtKeyAuthFailed, - mgmtKeyRetries)); + CultureInfo.CurrentCulture, + ExceptionMessages.YubiHsmAuthMgmtKeyAuthFailed, + mgmtKeyRetries)); } } @@ -443,15 +440,15 @@ public void DeleteCredential( /// /// The credential was not found. /// - public bool TryDeleteCredential( - ReadOnlyMemory managementKey, - string label, - [NotNullWhen(false)] out int? managementKeyRetries) + public bool TryDeleteCredential(ReadOnlyMemory managementKey, + string label, + [NotNullWhen(false)] out int? managementKeyRetries) { managementKeyRetries = null; DeleteCredentialCommand deleteCredCmd = new DeleteCredentialCommand(managementKey, label); + DeleteCredentialResponse deleteCredRsp = Connection.SendCommand(deleteCredCmd); @@ -460,6 +457,7 @@ public bool TryDeleteCredential( if (deleteCredRsp.Status == ResponseStatus.AuthenticationRequired) { managementKeyRetries = deleteCredRsp.RetriesRemaining!; + return false; } else diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/YubiHsmAuth/YubiHsmAuthSession.ManagementKey.cs b/Yubico.YubiKey/src/Yubico/YubiKey/YubiHsmAuth/YubiHsmAuthSession.ManagementKey.cs index 6890d55d..6823696b 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/YubiHsmAuth/YubiHsmAuthSession.ManagementKey.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/YubiHsmAuth/YubiHsmAuthSession.ManagementKey.cs @@ -25,23 +25,23 @@ namespace Yubico.YubiKey.YubiHsmAuth public partial class YubiHsmAuthSession { /// - /// Get the number of retries remaining for the management key. + /// Get the number of retries remaining for the management key. /// /// - /// There is a limit of 8 attempts to authenticate with the management key - /// before the management key is blocked. Once the management key is - /// blocked, the application must be reset before performing operations - /// which require authentication with the management key (such as adding - /// credentials, deleting credentials, and changing the management key). - /// To reset the application, see . - /// Supplying the correct management key before the management key is - /// blocked will reset the retry counter to 8. + /// There is a limit of 8 attempts to authenticate with the management key + /// before the management key is blocked. Once the management key is + /// blocked, the application must be reset before performing operations + /// which require authentication with the management key (such as adding + /// credentials, deleting credentials, and changing the management key). + /// To reset the application, see . + /// Supplying the correct management key before the management key is + /// blocked will reset the retry counter to 8. /// /// - /// The number of retries, as an integer. + /// The number of retries, as an integer. /// /// - /// The command to retrieve the number of retries failed. + /// The command to retrieve the number of retries failed. /// public int GetManagementKeyRetries() { @@ -57,90 +57,90 @@ public int GetManagementKeyRetries() } /// - /// Change the management key, using the - /// to retrieve the current and new management keys. + /// Change the management key, using the + /// to retrieve the current and new management keys. /// /// - /// - /// Compared to - /// which only attempts authentication once, this method automatically - /// retries authentication while there are retries remaining. - /// - /// - /// The management key is 16 bytes long, and is required when performing - /// operations that add or delete credentials ( - /// and - /// , respectively). - /// - /// - /// There is a limit of 8 attempts to authenticate with the management key - /// before the management key is blocked. Once the management key is - /// blocked, the application must be reset before performing operations - /// which require authentication with the management key (such as adding - /// credentials, deleting credentials, and changing the management key). - /// To reset the application, see . - /// Supplying the correct management key before the management key is - /// blocked will reset the retry counter to 8. - /// - /// - /// When the current and new management keys are needed, the - /// is called with - /// set to . - /// The KeyCollector gets the current and new management keys from the - /// user, saves them using - /// , - /// and returns true. Each key must be exactly 16 bytes long (see - /// ). If the - /// command succeeds (the management key is changed), this method returns - /// true. - /// - /// - /// If authentication with the current management key fails and there are - /// retries remaining, the KeyCollector will be called again with - /// the same Request, but will - /// be true and will be - /// set appropriately. When there are no retries remaining, a - /// will be thrown. - /// - /// - /// The only time this method returns false is when the - /// KeyCollector cancels the operation by returning false. - /// Cancellation usually happens when the user has clicked a "Cancel" - /// button. - /// - /// - /// In all situations, when this method ends, it will tell the - /// KeyCollector it is done by calling it with the Request - /// set to . - /// + /// + /// Compared to + /// which only attempts authentication once, this method automatically + /// retries authentication while there are retries remaining. + /// + /// + /// The management key is 16 bytes long, and is required when performing + /// operations that add or delete credentials ( + /// and + /// , respectively). + /// + /// + /// There is a limit of 8 attempts to authenticate with the management key + /// before the management key is blocked. Once the management key is + /// blocked, the application must be reset before performing operations + /// which require authentication with the management key (such as adding + /// credentials, deleting credentials, and changing the management key). + /// To reset the application, see . + /// Supplying the correct management key before the management key is + /// blocked will reset the retry counter to 8. + /// + /// + /// When the current and new management keys are needed, the + /// is called with + /// set to . + /// The KeyCollector gets the current and new management keys from the + /// user, saves them using + /// , + /// and returns true. Each key must be exactly 16 bytes long (see + /// ). If the + /// command succeeds (the management key is changed), this method returns + /// true. + /// + /// + /// If authentication with the current management key fails and there are + /// retries remaining, the KeyCollector will be called again with + /// the same Request, but will + /// be true and will be + /// set appropriately. When there are no retries remaining, a + /// will be thrown. + /// + /// + /// The only time this method returns false is when the + /// KeyCollector cancels the operation by returning false. + /// Cancellation usually happens when the user has clicked a "Cancel" + /// button. + /// + /// + /// In all situations, when this method ends, it will tell the + /// KeyCollector it is done by calling it with the Request + /// set to . + /// /// /// - /// True, when the management key has been changed successfully. - /// False when the KeyCollector returns false - /// (usually indicating user cancellation). + /// True, when the management key has been changed successfully. + /// False when the KeyCollector returns false + /// (usually indicating user cancellation). /// /// /// Authentication failed and there are no retries remaining. /// /// - /// A key collector was not supplied ( was - /// null). + /// A key collector was not supplied ( was + /// null). /// /// - /// Thrown when a management key has an invalid length. + /// Thrown when a management key has an invalid length. /// public bool TryChangeManagementKey() { - var keyCollector = GetKeyCollector(); + Func keyCollector = GetKeyCollector(); - var keyEntryData = new KeyEntryData() + var keyEntryData = new KeyEntryData { - Request = KeyEntryRequest.ChangeYubiHsmAuthManagementKey, + Request = KeyEntryRequest.ChangeYubiHsmAuthManagementKey }; try { - while (keyCollector(keyEntryData) == true) + while (keyCollector(keyEntryData)) { bool managementKeyChanged = TryChangeManagementKey( keyEntryData.GetCurrentValue(), @@ -178,66 +178,65 @@ public bool TryChangeManagementKey() } /// - /// Change the management key. + /// Change the management key. /// /// - /// - /// The management key is 16 bytes long, and is required when performing - /// operations that add or delete credentials ( - /// and - /// , respectively). - /// - /// - /// There is a limit of 8 attempts to authenticate with the management key - /// before the management key is blocked. Once the management key is - /// blocked, the application must be reset before performing operations - /// which require authentication with the management key (such as adding - /// credentials, deleting credentials, and changing the management key). - /// To reset the application, see . - /// Supplying the correct management key before the management key is - /// blocked will reset the retry counter to 8. - /// - /// - /// The caller is responsible for controlling the buffers which hold - /// the management keys and should overwrite the data after the command - /// is sent. The user's manual entry - /// "Sensitive Data" has further - /// details and recommendations for handling this kind of data. - /// + /// + /// The management key is 16 bytes long, and is required when performing + /// operations that add or delete credentials ( + /// and + /// , respectively). + /// + /// + /// There is a limit of 8 attempts to authenticate with the management key + /// before the management key is blocked. Once the management key is + /// blocked, the application must be reset before performing operations + /// which require authentication with the management key (such as adding + /// credentials, deleting credentials, and changing the management key). + /// To reset the application, see . + /// Supplying the correct management key before the management key is + /// blocked will reset the retry counter to 8. + /// + /// + /// The caller is responsible for controlling the buffers which hold + /// the management keys and should overwrite the data after the command + /// is sent. The user's manual entry + /// "Sensitive Data" has further + /// details and recommendations for handling this kind of data. + /// /// /// - /// True, when the management key has been changed successfully. False, - /// when authentication failed and the management key was not changed. - /// When this method returns false, - /// gives the number of retries remaining to authenticate with the - /// management key. + /// True, when the management key has been changed successfully. False, + /// when authentication failed and the management key was not changed. + /// When this method returns false, + /// gives the number of retries remaining to authenticate with the + /// management key. /// /// - /// The current value of the management key. It must be exactly 16 - /// bytes long (see ). - /// The default value is all zeros. + /// The current value of the management key. It must be exactly 16 + /// bytes long (see ). + /// The default value is all zeros. /// /// - /// The new value of the management key. It must be exactly 16 - /// bytes long (see ). + /// The new value of the management key. It must be exactly 16 + /// bytes long (see ). /// /// - /// When the command fails to authenticate the management key, this - /// value gives the number of retries remaining. + /// When the command fails to authenticate the management key, this + /// value gives the number of retries remaining. /// /// - /// Thrown when a management key has an invalid length. + /// Thrown when a management key has an invalid length. /// - public bool TryChangeManagementKey( - ReadOnlyMemory currentManagementKey, - ReadOnlyMemory newManagementKey, - [NotNullWhen(false)] - out int? retriesRemaining) + public bool TryChangeManagementKey(ReadOnlyMemory currentManagementKey, + ReadOnlyMemory newManagementKey, + [NotNullWhen(false)] out int? retriesRemaining) { retriesRemaining = null; - ChangeManagementKeyCommand changeMgmtKeyCmd = + var changeMgmtKeyCmd = new ChangeManagementKeyCommand(currentManagementKey, newManagementKey); + ChangeManagementKeyResponse changeMgmtKeyRsp = Connection.SendCommand(changeMgmtKeyCmd); @@ -245,54 +244,53 @@ public bool TryChangeManagementKey( { return true; } - else if (changeMgmtKeyRsp.Status == ResponseStatus.AuthenticationRequired) + + if (changeMgmtKeyRsp.Status == ResponseStatus.AuthenticationRequired) { retriesRemaining = changeMgmtKeyRsp.RetriesRemaining!; + return false; } - else - { - // We don't expect to receive any other response statuses, but - // just in case - throw new InvalidOperationException(changeMgmtKeyRsp.StatusMessage); - } + + // We don't expect to receive any other response statuses, but + // just in case + throw new InvalidOperationException(changeMgmtKeyRsp.StatusMessage); } /// - /// Change the management key, throw an exception if the operation failed. + /// Change the management key, throw an exception if the operation failed. /// /// - /// There is a limit of 8 attempts to authenticate with the management key - /// before the management key is blocked. Once the management key is - /// blocked, the application must be reset before performing operations - /// which require authentication with the management key (such as adding - /// credentials, deleting credentials, and changing the management key). - /// To reset the application, see . - /// Supplying the correct management key before the management key is - /// blocked will reset the retry counter to 8. + /// There is a limit of 8 attempts to authenticate with the management key + /// before the management key is blocked. Once the management key is + /// blocked, the application must be reset before performing operations + /// which require authentication with the management key (such as adding + /// credentials, deleting credentials, and changing the management key). + /// To reset the application, see . + /// Supplying the correct management key before the management key is + /// blocked will reset the retry counter to 8. /// /// - /// The current value of the management key. It must be exactly 16 - /// bytes long (see ). - /// The default value is all zeros. + /// The current value of the management key. It must be exactly 16 + /// bytes long (see ). + /// The default value is all zeros. /// /// - /// The new value of the management key. It must be exactly 16 - /// bytes long (see ). + /// The new value of the management key. It must be exactly 16 + /// bytes long (see ). /// /// - /// The was incorrect. + /// The was incorrect. /// - public void ChangeManagementKey( - ReadOnlyMemory currentManagementKey, - ReadOnlyMemory newManagementKey) + public void ChangeManagementKey(ReadOnlyMemory currentManagementKey, + ReadOnlyMemory newManagementKey) { if (!TryChangeManagementKey(currentManagementKey, newManagementKey, out int? retryCount)) { throw new SecurityException(string.Format( - CultureInfo.CurrentCulture, - ExceptionMessages.YubiHsmAuthMgmtKeyAuthFailed, - retryCount)); + CultureInfo.CurrentCulture, + ExceptionMessages.YubiHsmAuthMgmtKeyAuthFailed, + retryCount)); } } } diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/YubiHsmAuth/YubiHsmAuthSession.SessionKeys.cs b/Yubico.YubiKey/src/Yubico/YubiKey/YubiHsmAuth/YubiHsmAuthSession.SessionKeys.cs index 82781a79..738fe523 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/YubiHsmAuth/YubiHsmAuthSession.SessionKeys.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/YubiHsmAuth/YubiHsmAuthSession.SessionKeys.cs @@ -13,12 +13,10 @@ // limitations under the License. using System; -using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Security; -using System.Threading; using System.Threading.Tasks; using Yubico.YubiKey.YubiHsmAuth.Commands; @@ -99,9 +97,9 @@ public partial class YubiHsmAuthSession /// The operation timed out waiting for touch. /// public SessionKeys GetAes128SessionKeys(string credentialLabel, - ReadOnlyMemory credentialPassword, - ReadOnlyMemory hostChallenge, - ReadOnlyMemory hsmDeviceChallenge) + ReadOnlyMemory credentialPassword, + ReadOnlyMemory hostChallenge, + ReadOnlyMemory hsmDeviceChallenge) { GetAes128SessionKeysCommand getKeysCmd = new GetAes128SessionKeysCommand( @@ -109,6 +107,7 @@ public SessionKeys GetAes128SessionKeys(string credentialLabel, credentialPassword, hostChallenge, hsmDeviceChallenge); + GetAes128SessionKeysResponse getKeysRsp = Connection.SendCommand(getKeysCmd); @@ -117,9 +116,9 @@ public SessionKeys GetAes128SessionKeys(string credentialLabel, if (getKeysRsp.Status == ResponseStatus.AuthenticationRequired) { throw new SecurityException(string.Format( - CultureInfo.CurrentCulture, - ExceptionMessages.YubiHsmAuthCredPasswordAuthFailed, - getKeysRsp.RetriesRemaining)); + CultureInfo.CurrentCulture, + ExceptionMessages.YubiHsmAuthCredPasswordAuthFailed, + getKeysRsp.RetriesRemaining)); } else if (getKeysRsp.Status == ResponseStatus.RetryWithTouch) { @@ -223,19 +222,19 @@ public SessionKeys GetAes128SessionKeys(string credentialLabel, /// The operation timed out waiting for touch. /// public bool TryGetAes128SessionKeys(string credentialLabel, - ReadOnlyMemory hostChallenge, - ReadOnlyMemory hsmDeviceChallenge, - [NotNullWhen(true)] out SessionKeys? sessionKeys) + ReadOnlyMemory hostChallenge, + ReadOnlyMemory hsmDeviceChallenge, + [NotNullWhen(true)] out SessionKeys? sessionKeys) { sessionKeys = null; // Check if this credential requires touch - bool touchRequired = + bool touchRequired = ListCredentials() - .Single(c => c.Credential.Label == credentialLabel) - .Credential.TouchRequired; + .Single(c => c.Credential.Label == credentialLabel) + .Credential.TouchRequired; - var keyCollector = GetKeyCollector(); + Func? keyCollector = GetKeyCollector(); var keyEntryData = new KeyEntryData() { @@ -244,9 +243,9 @@ public bool TryGetAes128SessionKeys(string credentialLabel, try { - while (keyCollector(keyEntryData) == true) + while (keyCollector(keyEntryData)) { - GetAes128SessionKeysCommand getKeysCmd = + var getKeysCmd = new GetAes128SessionKeysCommand( credentialLabel, keyEntryData.GetCurrentValue(), @@ -259,7 +258,8 @@ public bool TryGetAes128SessionKeys(string credentialLabel, // new thread and send a touch request to the key collector keyEntryData.Request = KeyEntryRequest.TouchRequest; - var touchNotifyTask = Task.Run(() => keyCollector(keyEntryData)); + _ = Task.Run(() => keyCollector(keyEntryData)); + // We ignore the return value, regardless. So no need to wait. } @@ -269,6 +269,7 @@ public bool TryGetAes128SessionKeys(string credentialLabel, if (getKeysRsp.Status == ResponseStatus.Success) { sessionKeys = getKeysRsp.GetData(); + return true; } @@ -288,6 +289,7 @@ public bool TryGetAes128SessionKeys(string credentialLabel, keyEntryData.Request = KeyEntryRequest.AuthenticateYubiHsmAuthCredentialPassword; keyEntryData.IsRetry = true; keyEntryData.RetriesRemaining = getKeysRsp.RetriesRemaining; + continue; } else if (getKeysRsp.Status == ResponseStatus.RetryWithTouch) diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/YubiKeyApplication.cs b/Yubico.YubiKey/src/Yubico/YubiKey/YubiKeyApplication.cs index 0a21f5d8..7cc40985 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/YubiKeyApplication.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/YubiKeyApplication.cs @@ -35,15 +35,15 @@ public enum YubiKeyApplication internal static class YubiKeyApplicationExtensions { private static readonly byte[] ManagementAppId = new byte[] { 0xa0, 0x00, 0x00, 0x05, 0x27, 0x47, 0x11, 0x17 }; - private static readonly byte[] OtpAppId = new byte[] { 0xa0, 0x00, 0x00, 0x05, 0x27, 0x20, 0x01, 0x01 }; - private static readonly byte[] FidoU2fAppId = new byte[] { 0xa0, 0x00, 0x00, 0x06, 0x47, 0x2f, 0x00, 0x01 }; - private static readonly byte[] Fido2AppId = new byte[] { 0xa0, 0x00, 0x00, 0x06, 0x47, 0x2f, 0x00, 0x01 }; - private static readonly byte[] OathAppId = new byte[] { 0xa0, 0x00, 0x00, 0x05, 0x27, 0x21, 0x01 }; - private static readonly byte[] OpenPgpAppId = new byte[] { 0xd2, 0x76, 0x00, 0x01, 0x24, 0x01 }; - private static readonly byte[] PivAppId = new byte[] { 0xa0, 0x00, 0x00, 0x03, 0x08 }; - private static readonly byte[] OtpNdef = new byte[] { 0xd2, 0x76, 0x00, 0x00, 0x85, 0x01, 0x01 }; - private static readonly byte[] YubiHsmAuthId = new byte[] { 0xa0, 0x00, 0x00, 0x05, 0x27, 0x21, 0x07, 0x01 }; - private static readonly byte[] Scp03AuthId = new byte[] { 0xA0, 0x00, 0x00, 0x01, 0x51, 0x00, 0x00, 0x00 }; + private static readonly byte[] OtpAppId = new byte[] { 0xa0, 0x00, 0x00, 0x05, 0x27, 0x20, 0x01, 0x01 }; + private static readonly byte[] FidoU2fAppId = new byte[] { 0xa0, 0x00, 0x00, 0x06, 0x47, 0x2f, 0x00, 0x01 }; + private static readonly byte[] Fido2AppId = new byte[] { 0xa0, 0x00, 0x00, 0x06, 0x47, 0x2f, 0x00, 0x01 }; + private static readonly byte[] OathAppId = new byte[] { 0xa0, 0x00, 0x00, 0x05, 0x27, 0x21, 0x01 }; + private static readonly byte[] OpenPgpAppId = new byte[] { 0xd2, 0x76, 0x00, 0x01, 0x24, 0x01 }; + private static readonly byte[] PivAppId = new byte[] { 0xa0, 0x00, 0x00, 0x03, 0x08 }; + private static readonly byte[] OtpNdef = new byte[] { 0xd2, 0x76, 0x00, 0x00, 0x85, 0x01, 0x01 }; + private static readonly byte[] YubiHsmAuthId = new byte[] { 0xa0, 0x00, 0x00, 0x05, 0x27, 0x21, 0x07, 0x01 }; + private static readonly byte[] Scp03AuthId = new byte[] { 0xA0, 0x00, 0x00, 0x01, 0x51, 0x00, 0x00, 0x00 }; public static byte[] GetIso7816ApplicationId(this YubiKeyApplication application) => application switch diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/YubiKeyDevice.Instance.cs b/Yubico.YubiKey/src/Yubico/YubiKey/YubiKeyDevice.Instance.cs index 85632583..207d3549 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/YubiKeyDevice.Instance.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/YubiKeyDevice.Instance.cs @@ -340,7 +340,7 @@ private bool TryConnectScp03( out IScp03YubiKeyConnection connection) { IYubiKeyConnection? returnValue = Connect(application, applicationId, scp03Keys); - if (!(returnValue is null) && (returnValue is IScp03YubiKeyConnection scp03Connection)) + if (!(returnValue is null) && returnValue is IScp03YubiKeyConnection scp03Connection) { connection = scp03Connection; return true; @@ -368,7 +368,7 @@ private bool TryConnectScp03( _log.LogInformation( "YubiKey {Serial} connecting to {Application} application" + (scp03Keys is null ? "." : " over SCP03."), SerialNumber, - application is null ? (applicationId is null ? "Unknown" : applicationId.ToString()) + application is null ? applicationId is null ? "Unknown" : applicationId.ToString() : Enum.GetName(typeof(YubiKeyApplication), application)); if (application is null) @@ -377,7 +377,7 @@ private bool TryConnectScp03( { _log.LogInformation("Connecting via the SmartCard interface."); WaitForReclaimTimeout(Transport.SmartCard); - return (scp03Keys is null) ? + return scp03Keys is null ? new CcidConnection(_smartCardDevice, applicationId) : new Scp03CcidConnection(_smartCardDevice, applicationId, scp03Keys); } diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/YubiKeyDevice.Static.cs b/Yubico.YubiKey/src/Yubico/YubiKey/YubiKeyDevice.Static.cs index b038b9c2..7a0db8d3 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/YubiKeyDevice.Static.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/YubiKeyDevice.Static.cs @@ -12,16 +12,16 @@ // See the License for the specific language governing permissions and // limitations under the License. +using System; using System.Collections.Generic; -using System.Linq; using System.Globalization; -using Yubico.YubiKey.DeviceExtensions; +using System.Linq; using Yubico.Core.Devices; using Yubico.Core.Devices.Hid; using Yubico.Core.Devices.SmartCard; -using Yubico.PlatformInterop; -using System; using Yubico.Core.Logging; +using Yubico.PlatformInterop; +using Yubico.YubiKey.DeviceExtensions; namespace Yubico.YubiKey { @@ -116,9 +116,8 @@ public static IEnumerable FindByTransport(Transport transport = /// A bool indicating whether the YubiKey was found. public static bool TryGetYubiKey(int serialNumber, out IYubiKeyDevice yubiKey) { - yubiKey = FindAll() - .FirstOrDefault(k => k.SerialNumber == serialNumber); - return yubiKey != default; + yubiKey = FindAll().FirstOrDefault(k => k.SerialNumber == serialNumber); + return yubiKey != null; } internal class YubicoDeviceWithInfo @@ -136,10 +135,10 @@ public YubicoDeviceWithInfo(IDevice device) Info = GetDeviceInfo(); } - public override bool Equals(object obj) + public override bool Equals(object? obj) { // Check for null and compare run-time types - if ((obj == null) || !GetType().Equals(obj.GetType())) + if (obj == null || !GetType().Equals(obj.GetType())) { return false; } diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/YubiKeyDeviceInfo.cs b/Yubico.YubiKey/src/Yubico/YubiKey/YubiKeyDeviceInfo.cs index bb1c0b4d..27c1a0c0 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/YubiKeyDeviceInfo.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/YubiKeyDeviceInfo.cs @@ -286,48 +286,48 @@ internal YubiKeyDeviceInfo Merge(YubiKeyDeviceInfo? second) second ??= new YubiKeyDeviceInfo(); return new YubiKeyDeviceInfo - { - AvailableUsbCapabilities = AvailableUsbCapabilities | second.AvailableUsbCapabilities, + { + AvailableUsbCapabilities = AvailableUsbCapabilities | second.AvailableUsbCapabilities, - EnabledUsbCapabilities = EnabledUsbCapabilities | second.EnabledUsbCapabilities, + EnabledUsbCapabilities = EnabledUsbCapabilities | second.EnabledUsbCapabilities, - AvailableNfcCapabilities = AvailableNfcCapabilities | second.AvailableNfcCapabilities, + AvailableNfcCapabilities = AvailableNfcCapabilities | second.AvailableNfcCapabilities, - EnabledNfcCapabilities = EnabledNfcCapabilities | second.EnabledNfcCapabilities, + EnabledNfcCapabilities = EnabledNfcCapabilities | second.EnabledNfcCapabilities, - SerialNumber = SerialNumber ?? second.SerialNumber, + SerialNumber = SerialNumber ?? second.SerialNumber, - IsFipsSeries = IsFipsSeries || second.IsFipsSeries, + IsFipsSeries = IsFipsSeries || second.IsFipsSeries, - FormFactor = + FormFactor = FormFactor != FormFactor.Unknown ? FormFactor : second.FormFactor, - FirmwareVersion = + FirmwareVersion = FirmwareVersion != new FirmwareVersion() ? FirmwareVersion : second.FirmwareVersion, - AutoEjectTimeout = + AutoEjectTimeout = DeviceFlags.HasFlag(DeviceFlags.TouchEject) ? AutoEjectTimeout : second.DeviceFlags.HasFlag(DeviceFlags.TouchEject) ? second.AutoEjectTimeout : default, - ChallengeResponseTimeout = + ChallengeResponseTimeout = ChallengeResponseTimeout != default ? ChallengeResponseTimeout : second.ChallengeResponseTimeout, - DeviceFlags = DeviceFlags | second.DeviceFlags, + DeviceFlags = DeviceFlags | second.DeviceFlags, - ConfigurationLocked = + ConfigurationLocked = ConfigurationLocked != default ? ConfigurationLocked : second.ConfigurationLocked, - }; + }; } /// diff --git a/Yubico.YubiKey/tests/integration/Yubico.YubiKey.IntegrationTests.csproj b/Yubico.YubiKey/tests/integration/Yubico.YubiKey.IntegrationTests.csproj index 76b31eb4..fe7ebf6d 100644 --- a/Yubico.YubiKey/tests/integration/Yubico.YubiKey.IntegrationTests.csproj +++ b/Yubico.YubiKey/tests/integration/Yubico.YubiKey.IntegrationTests.csproj @@ -31,6 +31,7 @@ limitations under the License. --> + @@ -38,9 +39,9 @@ limitations under the License. --> - - - + + + diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Cryptography/RsaOaepTimingTests.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Cryptography/RsaOaepTimingTests.cs index b1e0f2ca..d0bcd9df 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Cryptography/RsaOaepTimingTests.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Cryptography/RsaOaepTimingTests.cs @@ -13,13 +13,15 @@ // limitations under the License. using System; +using System.Diagnostics; using System.Security.Cryptography; -using Yubico.YubiKey.TestUtilities; using Xunit; using Xunit.Abstractions; +using Yubico.YubiKey.TestUtilities; namespace Yubico.YubiKey.Cryptography { + [Trait("Category", "Simple")] public class RsaOaepTimingTests { private const int IterationCount1024 = 200000; @@ -28,6 +30,7 @@ public class RsaOaepTimingTests private readonly ITestOutputHelper _output; private readonly RandomNumberGenerator _random; + public RsaOaepTimingTests(ITestOutputHelper output) { _output = output; @@ -286,7 +289,7 @@ private static long RunTimerOaep(byte[] formattedData, int digestFlag, int expec } byte[] outputData = Array.Empty(); - var timer = System.Diagnostics.Stopwatch.StartNew(); + var timer = Stopwatch.StartNew(); for (int index = 0; index < iterationCount; index++) { isValid = RsaFormat.TryParsePkcs1Oaep(formattedData, digestFlag, out outputData); @@ -346,7 +349,7 @@ public static byte[] FormatOaepWrong( int digestLength = digester.HashSize / 8; - if ((inputData.Length == 0) || (inputData.Length > (buffer.Length - ((2 * digestLength) + 2)))) + if (inputData.Length == 0 || inputData.Length > buffer.Length - ((2 * digestLength) + 2)) { throw new ArgumentException("invalid length"); } diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Cryptography/RsaP1TimingTests.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Cryptography/RsaP1TimingTests.cs index 9ba2bba7..956e7d64 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Cryptography/RsaP1TimingTests.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Cryptography/RsaP1TimingTests.cs @@ -13,13 +13,15 @@ // limitations under the License. using System; +using System.Diagnostics; using System.Security.Cryptography; -using Yubico.YubiKey.TestUtilities; using Xunit; using Xunit.Abstractions; +using Yubico.YubiKey.TestUtilities; namespace Yubico.YubiKey.Cryptography { + [Trait("Category", "Simple")] public class RsaP1TimingTests { private const int IterationCount1024 = 10000000; @@ -40,7 +42,7 @@ public RsaP1TimingTests(ITestOutputHelper output) public void CorrectPad_Time(int keySizeBits) { bool isValid = false; - int[] dataLength = new int[] { 16, 24, 32, 48 }; + int[] dataLength = { 16, 24, 32, 48 }; for (int index = 0; index < dataLength.Length; index++) { @@ -62,7 +64,7 @@ public void CorrectPad_Time(int keySizeBits) public void FirstByteWrong_Time(int keySizeBits) { bool isValid = false; - int[] dataLength = new int[] { 16, 24, 32, 48 }; + int[] dataLength = { 16, 24, 32, 48 }; for (int index = 0; index < dataLength.Length; index++) { @@ -85,7 +87,7 @@ public void FirstByteWrong_Time(int keySizeBits) public void SecondByteWrong_Time(int keySizeBits) { bool isValid = false; - int[] dataLength = new int[] { 16, 24, 32, 48 }; + int[] dataLength = { 16, 24, 32, 48 }; for (int index = 0; index < dataLength.Length; index++) { @@ -108,7 +110,7 @@ public void SecondByteWrong_Time(int keySizeBits) public void NotEnoughPad_Time(int keySizeBits) { bool isValid = false; - int[] dataLength = new int[] { 16, 24, 32, 48 }; + int[] dataLength = { 16, 24, 32, 48 }; for (int index = 0; index < dataLength.Length; index++) { @@ -131,7 +133,7 @@ public void NotEnoughPad_Time(int keySizeBits) public void MultipleErrors_Time(int keySizeBits) { bool isValid = false; - int[] dataLength = new int[] { 16, 24, 32, 48 }; + int[] dataLength = { 16, 24, 32, 48 }; for (int index = 0; index < dataLength.Length; index++) { @@ -185,7 +187,7 @@ private static long RunTimerP15(byte[] formattedData, int expectedLength, out bo } byte[] outputData = Array.Empty(); - var timer = System.Diagnostics.Stopwatch.StartNew(); + var timer = Stopwatch.StartNew(); for (int index = 0; index < iterationCount; index++) { isValid = RsaFormat.TryParsePkcs1Decrypt(formattedData, out outputData); @@ -215,7 +217,7 @@ private void WriteResult(string scheme, int keySizeBits, int dataLength, int err _ => "all correct", }; - _output.WriteLine ( + _output.WriteLine( scheme + " " + keySizeBits + ", " + "data length = " + dataLength + ", " + message + "\n" + " total time: {0}", totalTime); } diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/BioEnrollTests.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/BioEnrollTests.cs index 9570ec97..12193b94 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/BioEnrollTests.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/BioEnrollTests.cs @@ -13,14 +13,15 @@ // limitations under the License. using System; -using System.Text; using System.Collections.Generic; +using System.Text; using Xunit; using Yubico.YubiKey.Fido2.Commands; using Yubico.YubiKey.TestUtilities; namespace Yubico.YubiKey.Fido2 { + [Trait("Category", "RequiresBio")] public class BioEnrollTests : SimpleIntegrationTestConnection { // Set to 0 meaning don't cancel. @@ -30,14 +31,14 @@ public class BioEnrollTests : SimpleIntegrationTestConnection // (cancel before any fingerprints are sampled). // If the call is touch or verify fingerprint, then any non-zero // _callCancelCount value means cancel when the request comes in. - private int _callCancelCount = 0; + private int _callCancelCount; public BioEnrollTests() - : base(YubiKeyApplication.Fido2, StandardTestDevice.Bio) + : base(YubiKeyApplication.Fido2, StandardTestDevice.Fw5Bio) { } - [Fact] + [SkippableFact(typeof(DeviceNotFoundException))] public void GetModality_Succeeds() { using (var fido2Session = new Fido2Session(Device)) @@ -48,7 +49,7 @@ public void GetModality_Succeeds() } } - [Fact] + [SkippableFact(typeof(DeviceNotFoundException))] public void GetSensorInfo_Succeeds() { using (var fido2Session = new Fido2Session(Device)) @@ -61,7 +62,7 @@ public void GetSensorInfo_Succeeds() } } - [Fact] + [SkippableFact(typeof(DeviceNotFoundException))] public void EnrollFingerprint_Succeeds() { string firstName = "SomeName"; @@ -86,8 +87,7 @@ public void EnrollFingerprint_Succeeds() { if (info.FriendlyName.Equals(secondName)) { - isValid = MemoryExtensions.SequenceEqual( - info.TemplateId.Span, templateInfo.TemplateId.Span); + isValid = info.TemplateId.Span.SequenceEqual(templateInfo.TemplateId.Span); if (isValid) { @@ -107,8 +107,7 @@ public void EnrollFingerprint_Succeeds() // is still there, it failed, so set it to false. foreach (TemplateInfo info in fpList) { - if (MemoryExtensions.SequenceEqual( - info.TemplateId.Span, templateInfo.TemplateId.Span)) + if (info.TemplateId.Span.SequenceEqual(templateInfo.TemplateId.Span)) { isValid = false; break; @@ -119,7 +118,7 @@ public void EnrollFingerprint_Succeeds() } } - [Theory] + [SkippableTheory(typeof(DeviceNotFoundException))] [InlineData(4)] [InlineData(-1)] public void EnrollFingerprint_Cancel_ThrowsCorrect(int cancelCount) @@ -136,9 +135,9 @@ public void EnrollFingerprint_Cancel_ThrowsCorrect(int cancelCount) private bool LocalKeyCollector(KeyEntryData arg) { - bool callCancel = (_callCancelCount == 0) ? false : true; + bool callCancel = _callCancelCount == 0 ? false : true; - if ((_callCancelCount > 0) && (!(arg.LastBioEnrollSampleResult is null))) + if (_callCancelCount > 0 && !(arg.LastBioEnrollSampleResult is null)) { if (arg.LastBioEnrollSampleResult.RemainingSampleCount != _callCancelCount) { diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/Commands/BioEnrollmentCommandTests.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/Commands/BioEnrollmentCommandTests.cs index 44a45a54..ffd90112 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/Commands/BioEnrollmentCommandTests.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/Commands/BioEnrollmentCommandTests.cs @@ -12,21 +12,22 @@ // See the License for the specific language governing permissions and // limitations under the License. +using System.Collections.Generic; +using Xunit; using Yubico.YubiKey.Fido2.PinProtocols; using Yubico.YubiKey.TestUtilities; -using Xunit; -using System.Collections.Generic; namespace Yubico.YubiKey.Fido2.Commands { + [Trait("Category", "RequiresBio")] public class BioEnrollmentCommandTests : NeedPinToken { public BioEnrollmentCommandTests() - : base(YubiKeyApplication.Fido2, StandardTestDevice.Bio, null) + : base(YubiKeyApplication.Fido2, StandardTestDevice.Fw5Bio, null) { } - [Fact] + [SkippableFact(typeof(DeviceNotFoundException))] public void GetModalityCommand_Succeeds() { var cmd = new GetBioModalityCommand(); @@ -36,7 +37,7 @@ public void GetModalityCommand_Succeeds() Assert.Equal(1, modality); } - [Fact] + [SkippableFact(typeof(DeviceNotFoundException))] public void GetSensorInfoCommand_Succeeds() { var cmd = new GetFingerprintSensorInfoCommand(); @@ -48,7 +49,7 @@ public void GetSensorInfoCommand_Succeeds() Assert.Equal(15, sensorInfo.MaxFriendlyNameBytes); } - [Fact] + [SkippableFact(typeof(DeviceNotFoundException))] public void BioEnrollBegin_Succeeds() { var protocol = new PinUvAuthProtocolTwo(); @@ -63,7 +64,7 @@ public void BioEnrollBegin_Succeeds() Assert.Equal(BioEnrollSampleStatus.FpGood, enrollResult.LastEnrollSampleStatus); } - [Fact] + [SkippableFact(typeof(DeviceNotFoundException))] public void BioEnrollNextSample_Succeeds() { var protocol = new PinUvAuthProtocolTwo(); @@ -88,7 +89,7 @@ public void BioEnrollNextSample_Succeeds() Assert.Equal(0, enrollResult.RemainingSampleCount); } - [Fact] + [SkippableFact(typeof(DeviceNotFoundException))] public void BioEnrollCancel_Succeeds() { var protocol = new PinUvAuthProtocolTwo(); @@ -114,7 +115,7 @@ public void BioEnrollCancel_Succeeds() Assert.Equal(ResponseStatus.Success, cancelRsp.Status); } - [Fact] + [SkippableFact(typeof(DeviceNotFoundException))] public void EnumerateEnrollmentsCommand_Succeeds() { var protocol = new PinUvAuthProtocolTwo(); @@ -131,7 +132,7 @@ public void EnumerateEnrollmentsCommand_Succeeds() _ = Assert.Single(templateInfos); } - [Fact] + [SkippableFact(typeof(DeviceNotFoundException))] public void FriendlyNameCommand_Succeeds() { var protocol = new PinUvAuthProtocolTwo(); @@ -152,7 +153,7 @@ public void FriendlyNameCommand_Succeeds() Assert.Equal(ResponseStatus.Success, nameRsp.Status); } - [Fact] + [SkippableFact(typeof(DeviceNotFoundException))] public void DeleteCommand_Succeeds() { var protocol = new PinUvAuthProtocolTwo(); diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/Commands/ConfigCommandTests.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/Commands/ConfigCommandTests.cs index 585c2324..003e6884 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/Commands/ConfigCommandTests.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/Commands/ConfigCommandTests.cs @@ -12,21 +12,21 @@ // See the License for the specific language governing permissions and // limitations under the License. +using Xunit; using Yubico.YubiKey.Fido2.PinProtocols; using Yubico.YubiKey.TestUtilities; -using Xunit; -using System.Collections.Generic; namespace Yubico.YubiKey.Fido2.Commands { + [Trait("Category", "RequiresBio")] public class ConfigCommandTests : NeedPinToken { public ConfigCommandTests() - : base(YubiKeyApplication.Fido2, StandardTestDevice.Bio, null) + : base(YubiKeyApplication.Fido2, StandardTestDevice.Fw5Bio, null) { } - [Fact] + [SkippableFact(typeof(DeviceNotFoundException))] public void EnableEnterpriseAttestationCommand_Succeeds() { var infoCmd = new GetInfoCommand(); @@ -51,7 +51,7 @@ public void EnableEnterpriseAttestationCommand_Succeeds() Assert.NotNull(authInfo.Options); } - [Fact] + [SkippableFact(typeof(DeviceNotFoundException))] public void ToggleAlwaysUvCommand_Succeeds() { var infoCmd = new GetInfoCommand(); @@ -76,7 +76,7 @@ public void ToggleAlwaysUvCommand_Succeeds() Assert.NotNull(authInfo.Options); } - [Fact] + [SkippableFact(typeof(DeviceNotFoundException))] public void SetMinPinLengthCommand_Pin_Succeeds() { var infoCmd = new GetInfoCommand(); @@ -101,7 +101,7 @@ public void SetMinPinLengthCommand_Pin_Succeeds() Assert.NotNull(authInfo.Options); } - [Fact] + [SkippableFact(typeof(DeviceNotFoundException))] public void SetMinPinLengthCommand_ForceChange_Succeeds() { var infoCmd = new GetInfoCommand(); @@ -125,8 +125,8 @@ public void SetMinPinLengthCommand_ForceChange_Succeeds() authInfo = infoRsp.GetData(); Assert.True(authInfo.ForcePinChange); - byte[] currentPin = new byte[] { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36 }; - byte[] newPin = new byte[] { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38 }; + byte[] currentPin = { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36 }; + byte[] newPin = { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38 }; var changePinCmd = new ChangePinCommand(protocol, currentPin, newPin); ChangePinResponse changePinRsp = Connection.SendCommand(changePinCmd); @@ -142,7 +142,7 @@ public void SetMinPinLengthCommand_ForceChange_Succeeds() Assert.Equal(ResponseStatus.Success, changePinRsp.Status); } - [Fact] + [SkippableFact(typeof(DeviceNotFoundException))] public void SetMinPinLengthCommand_AllNull_Succeeds() { var infoCmd = new GetInfoCommand(); diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/Commands/CredMetadataCommandTests.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/Commands/CredMetadataCommandTests.cs index 7cea2948..2dcf3d03 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/Commands/CredMetadataCommandTests.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/Commands/CredMetadataCommandTests.cs @@ -13,23 +13,23 @@ // limitations under the License. using System; +using Xunit; using Yubico.YubiKey.Fido2.PinProtocols; using Yubico.YubiKey.TestUtilities; -using Xunit; namespace Yubico.YubiKey.Fido2.Commands { public class CredMetadataCommandTests : SimpleIntegrationTestConnection { public CredMetadataCommandTests() - : base(YubiKeyApplication.Fido2, StandardTestDevice.Fw5) + : base(YubiKeyApplication.Fido2) { } [Fact] public void GetMetadataCommand_Succeeds() { - byte[] pin = new byte[] { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36 }; + byte[] pin = { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36 }; var protocol = new PinUvAuthProtocolTwo(); var getKeyCmd = new GetKeyAgreementCommand(protocol.Protocol); @@ -40,7 +40,10 @@ public void GetMetadataCommand_Succeeds() PinUvAuthTokenPermissions permissions = PinUvAuthTokenPermissions.CredentialManagement; var getTokenCmd = new GetPinUvAuthTokenUsingPinCommand(protocol, pin, permissions, null); GetPinUvAuthTokenResponse getTokenRsp = Connection.SendCommand(getTokenCmd); - Assert.Equal(ResponseStatus.Success, getTokenRsp.Status); + Assert.Equal(ResponseStatus.Success, getTokenRsp.Status); /*Xunit.Sdk.EqualException +Assert.Equal() Failure: Values differ +Expected: Success +Actual: Failed*/ ReadOnlyMemory pinToken = getTokenRsp.GetData(); var cmd = new GetCredentialMetadataCommand(pinToken, protocol); @@ -55,7 +58,7 @@ public void GetMetadataCommand_Succeeds() [Fact] public void GetMetadataCommand_Preview_Succeeds() { - byte[] pin = new byte[] { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36 }; + byte[] pin = { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36 }; var protocol = new PinUvAuthProtocolTwo(); var getKeyCmd = new GetKeyAgreementCommand(protocol.Protocol); @@ -66,6 +69,10 @@ public void GetMetadataCommand_Preview_Succeeds() var getTokenCmd = new GetPinTokenCommand(protocol, pin); GetPinUvAuthTokenResponse getTokenRsp = Connection.SendCommand(getTokenCmd); Assert.Equal(ResponseStatus.Success, getTokenRsp.Status); + /* Xunit.Sdk.EqualException +Assert.Equal() Failure: Values differ +Expected: Success +Actual: Failed*/ ReadOnlyMemory pinToken = getTokenRsp.GetData(); var cmd = new GetCredentialMetadataCommand(pinToken, protocol) diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/Commands/DeleteCredCommandTests.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/Commands/DeleteCredCommandTests.cs index f1554d42..e256cc2f 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/Commands/DeleteCredCommandTests.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/Commands/DeleteCredCommandTests.cs @@ -13,23 +13,24 @@ // limitations under the License. using System; +using Xunit; using Yubico.YubiKey.Fido2.PinProtocols; using Yubico.YubiKey.TestUtilities; -using Xunit; namespace Yubico.YubiKey.Fido2.Commands { + [Trait("Category", "RequiresBio")] public class DeleteCredCommandTests : SimpleIntegrationTestConnection { public DeleteCredCommandTests() - : base(YubiKeyApplication.Fido2, StandardTestDevice.Bio) + : base(YubiKeyApplication.Fido2, StandardTestDevice.Fw5Bio) { } - [Fact] + [SkippableFact(typeof(DeviceNotFoundException))] public void DeleteCredCommand_Succeeds() { - byte[] pin = new byte[] { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36 }; + byte[] pin = { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36 }; var protocol = new PinUvAuthProtocolTwo(); var getKeyCmd = new GetKeyAgreementCommand(protocol.Protocol); diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/Commands/EnumCredsCommandTests.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/Commands/EnumCredsCommandTests.cs index 90023bf5..96582d1b 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/Commands/EnumCredsCommandTests.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/Commands/EnumCredsCommandTests.cs @@ -13,24 +13,24 @@ // limitations under the License. using System; -using Yubico.YubiKey.TestUtilities; -using Yubico.YubiKey.Fido2.Commands; -using Yubico.YubiKey.Fido2.PinProtocols; using Xunit; +using Yubico.YubiKey.Fido2.PinProtocols; +using Yubico.YubiKey.TestUtilities; namespace Yubico.YubiKey.Fido2.Commands { + [Trait("Category", "FirmwareOrHardwareMissmatch")] public class EnumCredsCommandTests : SimpleIntegrationTestConnection { public EnumCredsCommandTests() - : base(YubiKeyApplication.Fido2, StandardTestDevice.Fw5) + : base(YubiKeyApplication.Fido2) { } [Fact] public void EnumCredsCommand_Succeeds() { - byte[] pin = new byte[] { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36 }; + byte[] pin = { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36 }; var protocol = new PinUvAuthProtocolTwo(); var getKeyCmd = new GetKeyAgreementCommand(protocol.Protocol); @@ -41,7 +41,10 @@ public void EnumCredsCommand_Succeeds() PinUvAuthTokenPermissions permissions = PinUvAuthTokenPermissions.CredentialManagement; var getTokenCmd = new GetPinUvAuthTokenUsingPinCommand(protocol, pin, permissions, null); GetPinUvAuthTokenResponse getTokenRsp = Connection.SendCommand(getTokenCmd); - Assert.Equal(ResponseStatus.Success, getTokenRsp.Status); + Assert.Equal(ResponseStatus.Success, getTokenRsp.Status); /*Xunit.Sdk.EqualException +Assert.Equal() Failure: Values differ +Expected: Success +Actual: Failed*/ ReadOnlyMemory pinToken = getTokenRsp.GetData(); var cmd = new EnumerateRpsBeginCommand(pinToken, protocol); @@ -73,7 +76,7 @@ public void EnumCredsCommand_Succeeds() [Fact] public void EnumCredsCommand_Preview_Succeeds() { - byte[] pin = new byte[] { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36 }; + byte[] pin = { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36 }; var protocol = new PinUvAuthProtocolOne(); var getKeyCmd = new GetKeyAgreementCommand(protocol.Protocol); @@ -83,7 +86,7 @@ public void EnumCredsCommand_Preview_Succeeds() protocol.Encapsulate(getKeyRsp.GetData()); var getTokenCmd = new GetPinTokenCommand(protocol, pin); GetPinUvAuthTokenResponse getTokenRsp = Connection.SendCommand(getTokenCmd); - Assert.Equal(ResponseStatus.Success, getTokenRsp.Status); + Assert.Equal(ResponseStatus.Success, getTokenRsp.Status); //Fail ReadOnlyMemory pinToken = getTokenRsp.GetData(); var cmd = new EnumerateRpsBeginCommand(pinToken, protocol) @@ -109,7 +112,7 @@ public void EnumCredsCommand_Preview_Succeeds() for (int index = 1; index < credCount; index++) { - var getNextCmd = new EnumerateCredentialsGetNextCommand() + var getNextCmd = new EnumerateCredentialsGetNextCommand { IsPreview = true }; diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/Commands/EnumRpsCommandTests.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/Commands/EnumRpsCommandTests.cs index 7308056e..c8210a16 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/Commands/EnumRpsCommandTests.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/Commands/EnumRpsCommandTests.cs @@ -13,24 +13,24 @@ // limitations under the License. using System; -using Yubico.YubiKey.TestUtilities; -using Yubico.YubiKey.Fido2.Commands; -using Yubico.YubiKey.Fido2.PinProtocols; using Xunit; +using Yubico.YubiKey.Fido2.PinProtocols; +using Yubico.YubiKey.TestUtilities; namespace Yubico.YubiKey.Fido2.Commands { + [Trait("Category", "FirmwareOrHardwareMissmatch")] public class EnumRpsCommandTests : SimpleIntegrationTestConnection { public EnumRpsCommandTests() - : base(YubiKeyApplication.Fido2, StandardTestDevice.Fw5) + : base(YubiKeyApplication.Fido2) { } [Fact] public void EnumRpsCommand_Succeeds() { - byte[] pin = new byte[] { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36 }; + byte[] pin = { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36 }; var protocol = new PinUvAuthProtocolTwo(); var getKeyCmd = new GetKeyAgreementCommand(protocol.Protocol); @@ -41,9 +41,12 @@ public void EnumRpsCommand_Succeeds() PinUvAuthTokenPermissions permissions = PinUvAuthTokenPermissions.CredentialManagement; var getTokenCmd = new GetPinUvAuthTokenUsingPinCommand(protocol, pin, permissions, null); GetPinUvAuthTokenResponse getTokenRsp = Connection.SendCommand(getTokenCmd); - Assert.Equal(ResponseStatus.Success, getTokenRsp.Status); - ReadOnlyMemory pinToken = getTokenRsp.GetData(); + Assert.Equal(ResponseStatus.Success, getTokenRsp.Status); /*Xunit.Sdk.EqualException +Assert.Equal() Failure: Values differ +Expected: Success +Actual: Failed*/ + ReadOnlyMemory pinToken = getTokenRsp.GetData(); var cmd = new EnumerateRpsBeginCommand(pinToken, protocol); EnumerateRpsBeginResponse rsp = Connection.SendCommand(cmd); Assert.Equal(ResponseStatus.Success, rsp.Status); @@ -66,7 +69,7 @@ public void EnumRpsCommand_Succeeds() [Fact] public void EnumRpsCommand_Preview_Succeeds() { - byte[] pin = new byte[] { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36 }; + byte[] pin = { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36 }; var protocol = new PinUvAuthProtocolTwo(); var getKeyCmd = new GetKeyAgreementCommand(protocol.Protocol); @@ -76,7 +79,10 @@ public void EnumRpsCommand_Preview_Succeeds() protocol.Encapsulate(getKeyRsp.GetData()); var getTokenCmd = new GetPinTokenCommand(protocol, pin); GetPinUvAuthTokenResponse getTokenRsp = Connection.SendCommand(getTokenCmd); - Assert.Equal(ResponseStatus.Success, getTokenRsp.Status); + Assert.Equal(ResponseStatus.Success, getTokenRsp.Status); /*Xunit.Sdk.EqualException +Assert.Equal() Failure: Values differ +Expected: Success +Actual: Failed*/ ReadOnlyMemory pinToken = getTokenRsp.GetData(); var cmd = new EnumerateRpsBeginCommand(pinToken, protocol) @@ -84,7 +90,10 @@ public void EnumRpsCommand_Preview_Succeeds() IsPreview = true }; EnumerateRpsBeginResponse rsp = Connection.SendCommand(cmd); - Assert.Equal(ResponseStatus.Success, rsp.Status); + Assert.Equal(ResponseStatus.Success, rsp.Status); /*Xunit.Sdk.EqualException +Assert.Equal() Failure: Values differ +Expected: Success +Actual: NoData*/ (int rpCount, RelyingParty rpZero) = rsp.GetData(); Assert.NotEqual(26, rpCount); @@ -92,7 +101,7 @@ public void EnumRpsCommand_Preview_Succeeds() for (int index = 1; index < rpCount; index++) { - var getNextCmd = new EnumerateRpsGetNextCommand() + var getNextCmd = new EnumerateRpsGetNextCommand { IsPreview = true }; diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/Commands/GetAssertionCommandTests.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/Commands/GetAssertionCommandTests.cs index dbe1612e..fc9cdfc5 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/Commands/GetAssertionCommandTests.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/Commands/GetAssertionCommandTests.cs @@ -12,22 +12,21 @@ // See the License for the specific language governing permissions and // limitations under the License. -using System; using Xunit; -using Yubico.YubiKey.TestUtilities; -using Yubico.YubiKey.Fido2.Commands; using Yubico.YubiKey.Fido2.PinProtocols; +using Yubico.YubiKey.TestUtilities; namespace Yubico.YubiKey.Fido2.Commands { + [Trait("Category", "RequiresBio")] public class GetAssertionCommandTests : NeedPinToken { public GetAssertionCommandTests() - : base(YubiKeyApplication.Fido2, StandardTestDevice.Bio, null) + : base(YubiKeyApplication.Fido2, StandardTestDevice.Fw5Bio, null) { } - [Fact] + [SkippableFact(typeof(DeviceNotFoundException))] public void GetAssertionCommand_Succeeds() { var protocol = new PinUvAuthProtocolTwo(); @@ -39,7 +38,7 @@ public void GetAssertionCommand_Succeeds() GetAssertionResponse rsp = Connection.SendCommand(cmd); Assert.Equal(ResponseStatus.Success, rsp.Status); GetAssertionData cData = rsp.GetData(); - if (!(cData.NumberOfCredentials is null) && (cData.NumberOfCredentials > 0)) + if (!(cData.NumberOfCredentials is null) && cData.NumberOfCredentials > 0) { int count = (int)cData.NumberOfCredentials; for (int index = 1; index < count; index++) @@ -57,7 +56,7 @@ private bool GetParams( PinUvAuthProtocolBase protocol, out GetAssertionParameters assertionParams) { - byte[] clientDataHash = new byte[] { + byte[] clientDataHash = { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38 }; diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/Commands/GetInfoCommandTests.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/Commands/GetInfoCommandTests.cs index da4d8144..6189b8df 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/Commands/GetInfoCommandTests.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/Commands/GetInfoCommandTests.cs @@ -12,18 +12,14 @@ // See the License for the specific language governing permissions and // limitations under the License. -using Yubico.YubiKey.TestUtilities; -using Yubico.YubiKey.Fido2.Commands; using Xunit; +using Yubico.YubiKey.TestUtilities; namespace Yubico.YubiKey.Fido2.Commands { public class GetInfoCommandTests : SimpleIntegrationTestConnection { - public GetInfoCommandTests() - : base(YubiKeyApplication.Fido2, StandardTestDevice.Fw5) - { - } + public GetInfoCommandTests() : base(YubiKeyApplication.Fido2) { } [Fact] public void GetInfoCommand_Succeeds() diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/Commands/GetKeyAgreeCommandTests.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/Commands/GetKeyAgreeCommandTests.cs index 3cac78d4..2f8e8c21 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/Commands/GetKeyAgreeCommandTests.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/Commands/GetKeyAgreeCommandTests.cs @@ -12,25 +12,25 @@ // See the License for the specific language governing permissions and // limitations under the License. -using Yubico.YubiKey.TestUtilities; -using Yubico.YubiKey.Fido2.Commands; -using Yubico.YubiKey.Fido2.Cose; using Xunit; +using Yubico.YubiKey.Fido2.Cose; using Yubico.YubiKey.Fido2.PinProtocols; +using Yubico.YubiKey.TestUtilities; namespace Yubico.YubiKey.Fido2.Commands { + [Trait("Category", "RequiresBio")] public class GetKeyAgreeCommandTests : SimpleIntegrationTestConnection { public GetKeyAgreeCommandTests() - : base(YubiKeyApplication.Fido2, StandardTestDevice.Bio) + : base(YubiKeyApplication.Fido2, StandardTestDevice.Fw5Bio) { } - [Fact] + [SkippableFact(typeof(DeviceNotFoundException))] public void GetKeyAgreeCommand_Succeeds() { - var cmd = new GetKeyAgreementCommand() { PinUvAuthProtocol = PinUvAuthProtocol.ProtocolTwo, }; + var cmd = new GetKeyAgreementCommand { PinUvAuthProtocol = PinUvAuthProtocol.ProtocolTwo, }; GetKeyAgreementResponse rsp = Connection.SendCommand(cmd); Assert.Equal(ResponseStatus.Success, rsp.Status); diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/Commands/HmacSecretTests.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/Commands/HmacSecretTests.cs index c0380f67..ea25ee55 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/Commands/HmacSecretTests.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/Commands/HmacSecretTests.cs @@ -14,12 +14,12 @@ using System; using Xunit; -using Yubico.YubiKey.TestUtilities; -using Yubico.YubiKey.Fido2.Commands; using Yubico.YubiKey.Fido2.PinProtocols; +using Yubico.YubiKey.TestUtilities; namespace Yubico.YubiKey.Fido2.Commands { + [Trait("Category", "RequiresBio")] public class HmacSecretTests : SimpleIntegrationTestConnection { private readonly byte[] _pin; @@ -31,7 +31,7 @@ public class HmacSecretTests : SimpleIntegrationTestConnection private readonly AuthenticatorInfo _deviceInfo; public HmacSecretTests() - : base(YubiKeyApplication.Fido2, StandardTestDevice.Bio) + : base(YubiKeyApplication.Fido2, StandardTestDevice.Fw5Bio) { _pin = new byte[] { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36 }; @@ -63,7 +63,7 @@ public HmacSecretTests() _deviceInfo = infoRsp.GetData(); } - [Fact] + [SkippableFact(typeof(DeviceNotFoundException))] public void MakeCredentialWithHmacSecret_Succeeds() { bool isValid = GetMakeCredentialParams(out MakeCredentialParameters makeParams); @@ -79,10 +79,10 @@ public void MakeCredentialWithHmacSecret_Succeeds() Assert.True(isValid); } - [Fact] + [SkippableFact(typeof(DeviceNotFoundException))] public void GetAssertionWithHmacSecret_Succeeds() { - byte[] salt1 = new byte[] { + byte[] salt1 = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08 }; @@ -90,7 +90,7 @@ public void GetAssertionWithHmacSecret_Succeeds() bool isValid = GetGetAssertionParams(out GetAssertionParameters assertionParams); Assert.True(isValid); - assertionParams.RequestHmacSecretExtension(salt1, null); + assertionParams.RequestHmacSecretExtension(salt1); assertionParams.EncodeHmacSecretExtension(_protocol); var cmd = new GetAssertionCommand(assertionParams); @@ -101,14 +101,14 @@ public void GetAssertionWithHmacSecret_Succeeds() Assert.True(hmacSecret.Length == 32); } - [Fact] + [SkippableFact(typeof(DeviceNotFoundException))] public void GetAssertionWithTwoHmacSecrets_Succeeds() { - byte[] salt1 = new byte[] { + byte[] salt1 = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08 }; - byte[] salt2 = new byte[] { + byte[] salt2 = { 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18 }; @@ -210,7 +210,7 @@ private bool GetPinToken( SetPinResponse setPinRsp = Connection.SendCommand(setPinCmd); status = setPinRsp.Status; - } while(status == ResponseStatus.Success); + } while (status == ResponseStatus.Success); return false; } diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/Commands/MakeCredBlobTests.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/Commands/MakeCredBlobTests.cs index 02f950ee..90310d0c 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/Commands/MakeCredBlobTests.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/Commands/MakeCredBlobTests.cs @@ -14,20 +14,20 @@ using System; using Xunit; -using Yubico.YubiKey.TestUtilities; -using Yubico.YubiKey.Fido2.Commands; using Yubico.YubiKey.Fido2.PinProtocols; +using Yubico.YubiKey.TestUtilities; namespace Yubico.YubiKey.Fido2.Commands { + [Trait("Category", "RequiresBio")] public class MakeCredBlobTests : NeedPinToken { - private readonly byte[] _clientDataHash = new byte[] { + private readonly byte[] _clientDataHash = { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38 }; - private readonly byte[] _credBlobValue = new byte[] { + private readonly byte[] _credBlobValue = { 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F, 0x50, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, @@ -46,11 +46,11 @@ public class MakeCredBlobTests : NeedPinToken }; public MakeCredBlobTests() - : base(YubiKeyApplication.Fido2, StandardTestDevice.Bio, null) + : base(YubiKeyApplication.Fido2, StandardTestDevice.Fw5Bio, null) { } - [Fact] + [SkippableFact(typeof(DeviceNotFoundException))] public void MakeCredentialBlob_Succeeds() { var protocol = new PinUvAuthProtocolTwo(); diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/Commands/MakeCredentialCommandTests.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/Commands/MakeCredentialCommandTests.cs index c3a53b36..8442cdd9 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/Commands/MakeCredentialCommandTests.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/Commands/MakeCredentialCommandTests.cs @@ -14,20 +14,20 @@ using System; using Xunit; -using Yubico.YubiKey.TestUtilities; -using Yubico.YubiKey.Fido2.Commands; using Yubico.YubiKey.Fido2.PinProtocols; +using Yubico.YubiKey.TestUtilities; namespace Yubico.YubiKey.Fido2.Commands { + [Trait("Category", "RequiresBio")] public class MakeCredentialCommandTests : NeedPinToken { public MakeCredentialCommandTests() - : base(YubiKeyApplication.Fido2, StandardTestDevice.Bio, null) + : base(YubiKeyApplication.Fido2, StandardTestDevice.Fw5Bio, null) { } - [Fact] + [SkippableFact(typeof(DeviceNotFoundException))] public void MakeCredentialCommand_Succeeds() { var protocol = new PinUvAuthProtocolTwo(); @@ -47,7 +47,7 @@ private bool GetParams( PinUvAuthProtocolBase protocol, out MakeCredentialParameters makeParams) { - byte[] clientDataHash = new byte[] { + byte[] clientDataHash = { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38 }; @@ -56,7 +56,7 @@ private bool GetParams( { Name = "SomeRpName", }; - byte[] userId = new byte[] { 0x11, 0x22, 0x33, 0x44 }; + byte[] userId = { 0x11, 0x22, 0x33, 0x44 }; var user = new UserEntity(new ReadOnlyMemory(userId)) { Name = "SomeUserName", diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/Commands/MakeLargeBlobTests.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/Commands/MakeLargeBlobTests.cs index 47fc4539..1e50a891 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/Commands/MakeLargeBlobTests.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/Commands/MakeLargeBlobTests.cs @@ -13,25 +13,23 @@ // limitations under the License. using System; -using System.Collections.Generic; using System.Security.Cryptography; using Xunit; -using Yubico.Core.Devices.Hid; using Yubico.YubiKey.Cryptography; -using Yubico.YubiKey.Fido2.Commands; using Yubico.YubiKey.Fido2.PinProtocols; using Yubico.YubiKey.TestUtilities; namespace Yubico.YubiKey.Fido2.Commands { + [Trait("Category", "RequiresBio")] public class MakeLargeBlobTests : NeedPinToken { public MakeLargeBlobTests() - : base(YubiKeyApplication.Fido2, StandardTestDevice.Bio, null) + : base(YubiKeyApplication.Fido2, StandardTestDevice.Fw5Bio, null) { } - [Fact] + [SkippableFact(typeof(DeviceNotFoundException))] public void InitialLargeBlob_Succeeds() { var getInfoCmd = new GetInfoCommand(); @@ -55,10 +53,10 @@ public void InitialLargeBlob_Succeeds() Assert.NotEmpty(blobData.ToArray()); } - [Fact] + [SkippableFact(typeof(DeviceNotFoundException))] public void SetLargeBlob_Succeeds() { - byte[] dataToStore = new byte[] { + byte[] dataToStore = { 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58 }; diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/Commands/NeedPinToken.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/Commands/NeedPinToken.cs index 47e4b157..c910578e 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/Commands/NeedPinToken.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/Commands/NeedPinToken.cs @@ -13,12 +13,6 @@ // limitations under the License. using System; -using System.Collections.Generic; -using System.Security.Cryptography; -using Xunit; -using Yubico.Core.Devices.Hid; -using Yubico.YubiKey.Cryptography; -using Yubico.YubiKey.Fido2.Commands; using Yubico.YubiKey.Fido2.PinProtocols; using Yubico.YubiKey.TestUtilities; @@ -26,9 +20,9 @@ namespace Yubico.YubiKey.Fido2.Commands { public class NeedPinToken : SimpleIntegrationTestConnection { - private readonly byte[] _pin = new byte[] { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36 }; + private readonly byte[] _pin; - public NeedPinToken(YubiKeyApplication application, StandardTestDevice device, byte[]? pin) + protected NeedPinToken(YubiKeyApplication application, StandardTestDevice device, byte[]? pin) : base(application, device) { if (pin is null) @@ -42,7 +36,7 @@ public NeedPinToken(YubiKeyApplication application, StandardTestDevice device, b } } - public bool GetPinToken( + protected bool GetPinToken( PinUvAuthProtocolBase protocol, PinUvAuthTokenPermissions permissions, out byte[] pinToken) @@ -69,7 +63,6 @@ public bool GetPinToken( else { var getTokenCmd = new GetPinUvAuthTokenUsingPinCommand(protocol, _pin, permissions, null); - //var getTokenCmd = new GetPinUvAuthTokenUsingUvCommand(protocol, permissions, null); getTokenRsp = Connection.SendCommand(getTokenCmd); } diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/Commands/SetPinCommandTests.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/Commands/SetPinCommandTests.cs index c577853b..55887134 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/Commands/SetPinCommandTests.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/Commands/SetPinCommandTests.cs @@ -14,28 +14,28 @@ using System; using Xunit; -using Yubico.YubiKey.TestUtilities; using Yubico.Core.Iso7816; -using Yubico.YubiKey.Fido2.Commands; using Yubico.YubiKey.Fido2.Cose; using Yubico.YubiKey.Fido2.PinProtocols; +using Yubico.YubiKey.TestUtilities; namespace Yubico.YubiKey.Fido2.Commands { + [Trait("Category", "RequiresBio")] public class SetPinCommandTests : SimpleIntegrationTestConnection { private const int Fido2AuthPin = 1; private const int Fido2AuthUv = 2; public SetPinCommandTests() - : base(YubiKeyApplication.Fido2, StandardTestDevice.Bio) + : base(YubiKeyApplication.Fido2, StandardTestDevice.Fw5Bio) { } - [Fact] + [SkippableFact(typeof(DeviceNotFoundException))] public void SetPinCommand_Succeeds() { - byte[] newPin = new byte[] { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36 }; + byte[] newPin = { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36 }; var resetCmd = new ResetCommand(); ResetResponse resetRsp = Connection.SendCommand(resetCmd); @@ -57,11 +57,11 @@ public void SetPinCommand_Succeeds() Assert.Equal(ResponseStatus.Success, setPinRsp.Status); } - [Fact] + [SkippableFact(typeof(DeviceNotFoundException))] public void ChangePinCommand_Succeeds() { - byte[] currentPin = new byte[] { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36 }; - byte[] newPin = new byte[] { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38 }; + byte[] currentPin = { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36 }; + byte[] newPin = { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38 }; var protocol = new PinUvAuthProtocolOne(); @@ -79,10 +79,10 @@ public void ChangePinCommand_Succeeds() Assert.Equal(ResponseStatus.Success, changePinRsp.Status); } - [Fact] + [SkippableFact(typeof(DeviceNotFoundException))] public void GetPinTokenCommand_Succeeds() { - byte[] currentPin = new byte[] { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36 }; + byte[] currentPin = { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36 }; var protocol = new PinUvAuthProtocolOne(); @@ -99,7 +99,7 @@ public void GetPinTokenCommand_Succeeds() GetPinUvAuthTokenResponse getTokenRsp = Connection.SendCommand(getTokenCmd); Assert.Equal(ResponseStatus.Success, getTokenRsp.Status); - int expectedLength = (protocol.Protocol == PinUvAuthProtocol.ProtocolOne) ? 32 : 48; + int expectedLength = protocol.Protocol == PinUvAuthProtocol.ProtocolOne ? 32 : 48; ReadOnlyMemory encryptedToken = getTokenRsp.GetData(); Assert.Equal(expectedLength, encryptedToken.Length); @@ -107,10 +107,10 @@ public void GetPinTokenCommand_Succeeds() Assert.Equal(32, token.Length); } - [Fact] + [SkippableFact(typeof(DeviceNotFoundException))] public void GetPinUvAuthTokenUsingPinCommand_Correct() { - byte[] currentPin = new byte[] { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36 }; + byte[] currentPin = { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36 }; bool isSupported = IsSupportedWithPermissions(Fido2AuthPin); @@ -138,7 +138,7 @@ public void GetPinUvAuthTokenUsingPinCommand_Correct() Assert.Equal(ResponseStatus.Success, getTokenRsp.Status); - int expectedLength = (protocol.Protocol == PinUvAuthProtocol.ProtocolOne) ? 32 : 48; + int expectedLength = protocol.Protocol == PinUvAuthProtocol.ProtocolOne ? 32 : 48; ReadOnlyMemory encryptedToken = getTokenRsp.GetData(); Assert.Equal(expectedLength, encryptedToken.Length); @@ -146,7 +146,7 @@ public void GetPinUvAuthTokenUsingPinCommand_Correct() Assert.Equal(32, token.Length); } - [Fact] + [SkippableFact(typeof(DeviceNotFoundException))] public void GetPinUvAuthTokenUsingUvCommand_Correct() { bool isSupported = IsSupportedWithPermissions(Fido2AuthUv); @@ -175,7 +175,7 @@ public void GetPinUvAuthTokenUsingUvCommand_Correct() Assert.Equal(ResponseStatus.Success, getTokenRsp.Status); - int expectedLength = (protocol.Protocol == PinUvAuthProtocol.ProtocolOne) ? 32 : 48; + int expectedLength = protocol.Protocol == PinUvAuthProtocol.ProtocolOne ? 32 : 48; ReadOnlyMemory encryptedToken = getTokenRsp.GetData(); Assert.Equal(expectedLength, encryptedToken.Length); @@ -189,7 +189,7 @@ public void GetPinUvAuthTokenUsingUvCommand_Correct() private bool IsSupportedWithPermissions(int auth) { string keyToken = "pinUvAuthToken"; - string keyAuth = (auth == Fido2AuthPin) ? "clientPin" : "uv"; + string keyAuth = auth == Fido2AuthPin ? "clientPin" : "uv"; var cmd = new GetInfoCommand(); GetInfoResponse rsp = Connection.SendCommand(cmd); Assert.Equal(ResponseStatus.Success, rsp.Status); diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/Commands/UpdateUserInfoCommandTests.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/Commands/UpdateUserInfoCommandTests.cs index e9b0ea76..77b2784a 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/Commands/UpdateUserInfoCommandTests.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/Commands/UpdateUserInfoCommandTests.cs @@ -13,23 +13,24 @@ // limitations under the License. using System; +using Xunit; using Yubico.YubiKey.Fido2.PinProtocols; using Yubico.YubiKey.TestUtilities; -using Xunit; namespace Yubico.YubiKey.Fido2.Commands { + [Trait("Category", "FirmwareOrHardwareMissmatch")] public class UpdateUserInfoCommandTests : SimpleIntegrationTestConnection { public UpdateUserInfoCommandTests() - : base(YubiKeyApplication.Fido2, StandardTestDevice.Fw5) + : base(YubiKeyApplication.Fido2) { } [Fact] public void UpdateInfoCommand_Succeeds() { - byte[] pin = new byte[] { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36 }; + byte[] pin = { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36 }; var protocol = new PinUvAuthProtocolTwo(); var getKeyCmd = new GetKeyAgreementCommand(protocol.Protocol); @@ -40,7 +41,10 @@ public void UpdateInfoCommand_Succeeds() PinUvAuthTokenPermissions permissions = PinUvAuthTokenPermissions.CredentialManagement; var getTokenCmd = new GetPinUvAuthTokenUsingPinCommand(protocol, pin, permissions, null); GetPinUvAuthTokenResponse getTokenRsp = Connection.SendCommand(getTokenCmd); - Assert.Equal(ResponseStatus.Success, getTokenRsp.Status); + Assert.Equal(ResponseStatus.Success, getTokenRsp.Status); /*Xunit.Sdk.EqualException +Assert.Equal() Failure: Values differ +Expected: Success +Actual: Failed*/ ReadOnlyMemory pinToken = getTokenRsp.GetData(); var cmd = new EnumerateRpsBeginCommand(pinToken, protocol); @@ -57,7 +61,7 @@ public void UpdateInfoCommand_Succeeds() (int credCount, CredentialUserInfo userInfo) = credRsp.GetData(); Assert.True(credCount != 0); - string origDisplayName = userInfo.User.DisplayName??""; + string origDisplayName = userInfo.User.DisplayName ?? ""; var newInfo = new UserEntity(userInfo.User.Id) { @@ -82,7 +86,7 @@ public void UpdateInfoCommand_Succeeds() [Fact] public void UpdateInfoCommand_Preview_Succeeds() { - byte[] pin = new byte[] { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36 }; + byte[] pin = { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36 }; var protocol = new PinUvAuthProtocolTwo(); var getKeyCmd = new GetKeyAgreementCommand(protocol.Protocol); @@ -92,7 +96,10 @@ public void UpdateInfoCommand_Preview_Succeeds() protocol.Encapsulate(getKeyRsp.GetData()); var getTokenCmd = new GetPinTokenCommand(protocol, pin); GetPinUvAuthTokenResponse getTokenRsp = Connection.SendCommand(getTokenCmd); - Assert.Equal(ResponseStatus.Success, getTokenRsp.Status); + Assert.Equal(ResponseStatus.Success, getTokenRsp.Status); /*Xunit.Sdk.EqualException +Assert.Equal() Failure: Values differ +Expected: Success +Actual: Failed*/ ReadOnlyMemory pinToken = getTokenRsp.GetData(); var cmd = new EnumerateRpsBeginCommand(pinToken, protocol) @@ -115,7 +122,7 @@ public void UpdateInfoCommand_Preview_Succeeds() (int credCount, CredentialUserInfo userInfo) = credRsp.GetData(); Assert.True(credCount != 0); - string origDisplayName = userInfo.User.DisplayName??""; + string origDisplayName = userInfo.User.DisplayName ?? ""; var newInfo = new UserEntity(userInfo.User.Id) { diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/ConfigTests.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/ConfigTests.cs index fdcee20f..3323dd87 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/ConfigTests.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/ConfigTests.cs @@ -13,17 +13,18 @@ // limitations under the License. using System; -using System.Text; using System.Collections.Generic; +using System.Text; using Xunit; using Yubico.YubiKey.TestUtilities; namespace Yubico.YubiKey.Fido2 { + [Trait("Category", "Simple")] public class ConfigTests : SimpleIntegrationTestConnection { public ConfigTests() - : base(YubiKeyApplication.Fido2, StandardTestDevice.Fw5) + : base(YubiKeyApplication.Fido2) { } @@ -35,16 +36,18 @@ public void EnableEnterpriseAttestation_Succeeds() fido2Session.KeyCollector = LocalKeyCollector; OptionValue optionValue = fido2Session.AuthenticatorInfo.GetOptionValue("ep"); + bool isSet = fido2Session.TryEnableEnterpriseAttestation(); - bool expectedResult = false; - if ((optionValue == OptionValue.True) || (optionValue == OptionValue.False)) + bool shouldSupportEnterpriseAttestation = optionValue == OptionValue.True || optionValue == OptionValue.False; + if (shouldSupportEnterpriseAttestation) { - expectedResult = true; + Assert.True(isSet); + } + else + { + Assert.False(isSet); } - bool isSet = fido2Session.TryEnableEnterpriseAttestation(); - - Assert.Equal(expectedResult, isSet); } } @@ -89,11 +92,11 @@ public void SetMinPinLen_Succeeds() bool expectedResult = optionValue == OptionValue.True; - bool isSet = fido2Session.TrySetPinConfig(6, null, null); + bool isSet = fido2Session.TrySetPinConfig(6); Assert.Equal(expectedResult, isSet); if (isSet) { - Assert.NotNull(fido2Session.AuthenticatorInfo.ForcePinChange); + _ = Assert.NotNull(fido2Session.AuthenticatorInfo.ForcePinChange); Assert.True(fido2Session.AuthenticatorInfo.ForcePinChange!); } } @@ -106,7 +109,7 @@ public void ForceChangePin_Succeeds() { fido2Session.KeyCollector = LocalKeyCollector; - Assert.NotNull(fido2Session.AuthenticatorInfo.ForcePinChange); + _ = Assert.NotNull(fido2Session.AuthenticatorInfo.ForcePinChange); // Does not work on my USBAKeychain 5.4.3 (Assert.NotNull() Failure: Value of type 'Nullable' does not have a value) Assert.False(fido2Session.AuthenticatorInfo.ForcePinChange!); OptionValue optionValue = fido2Session.AuthenticatorInfo.GetOptionValue("setMinPINLength"); @@ -117,7 +120,7 @@ public void ForceChangePin_Succeeds() Assert.Equal(expectedResult, isSet); if (isSet) { - Assert.NotNull(fido2Session.AuthenticatorInfo.ForcePinChange); + _ = Assert.NotNull(fido2Session.AuthenticatorInfo.ForcePinChange); Assert.True(fido2Session.AuthenticatorInfo.ForcePinChange!); } } @@ -133,13 +136,13 @@ public void SetRpId_Succeeds() OptionValue optionValue = fido2Session.AuthenticatorInfo.GetOptionValue("setMinPINLength"); bool isSupported = fido2Session.AuthenticatorInfo.IsExtensionSupported("minPinLength"); - bool expectedResult = (optionValue == OptionValue.True) && isSupported; + bool expectedResult = optionValue == OptionValue.True && isSupported; var rpList = new List(1) { "rpidOne" }; - bool isSet = fido2Session.TrySetPinConfig(null, rpList, null); + bool isSet = fido2Session.TrySetPinConfig(null, rpList); Assert.Equal(expectedResult, isSet); if (isSet) @@ -184,7 +187,7 @@ private bool VerifyExtension(Fido2Session fido2Session) } return isValid; - } + } private bool LocalKeyCollector(KeyEntryData arg) { diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/CredMgmtTests.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/CredMgmtTests.cs index 2cf3568d..81f31d38 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/CredMgmtTests.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/CredMgmtTests.cs @@ -20,6 +20,7 @@ namespace Yubico.YubiKey.Fido2 { + [Trait("Category", "RequiresBio")] public class CredMgmtTests : IClassFixture { private readonly BioFido2Fixture _bioFido2Fixture; @@ -27,15 +28,16 @@ public class CredMgmtTests : IClassFixture public CredMgmtTests(BioFido2Fixture bioFido2Fixture) { _bioFido2Fixture = bioFido2Fixture; - - if (!_bioFido2Fixture.HasCredentials) + if (_bioFido2Fixture.HasCredentials) { - _bioFido2Fixture.AddCredentials(2, 1); - _bioFido2Fixture.AddCredentials(1, 0); + return; } + + _bioFido2Fixture.AddCredentials(2, 1); + _bioFido2Fixture.AddCredentials(1, 0); } - [Fact] + [SkippableFact(typeof(DeviceNotFoundException))] public void GetMetadata_Succeeds() { using (var fido2Session = new Fido2Session(_bioFido2Fixture.Device)) @@ -50,7 +52,7 @@ public void GetMetadata_Succeeds() } } - [Fact] + [SkippableFact(typeof(DeviceNotFoundException))] public void EnumerateRps_Succeeds() { using (var fido2Session = new Fido2Session(_bioFido2Fixture.Device)) @@ -62,13 +64,12 @@ public void EnumerateRps_Succeeds() Assert.Equal(2, rpList.Count); RpInfo rpInfo = _bioFido2Fixture.MatchRelyingParty(rpList[0]); - bool isValid = MemoryExtensions.SequenceEqual( - rpInfo.RelyingPartyIdHash.Span, rpList[0].RelyingPartyIdHash.Span); + bool isValid = rpInfo.RelyingPartyIdHash.Span.SequenceEqual(rpList[0].RelyingPartyIdHash.Span); Assert.True(isValid); } } - [Fact] + [SkippableFact(typeof(DeviceNotFoundException))] public void EnumerateCreds_Succeeds() { using (var fido2Session = new Fido2Session(_bioFido2Fixture.Device)) @@ -83,25 +84,25 @@ public void EnumerateCreds_Succeeds() UserEntity ykUser = ykCredList[0].User; - Tuple userInfo = _bioFido2Fixture.MatchUser(rpInfo.RelyingParty, ykUser); + Tuple userInfo = _bioFido2Fixture.MatchUser(rpInfo.RelyingParty, ykUser); ReadOnlyMemory targetKey = userInfo.Item2.LargeBlobKey ?? throw new InvalidOperationException("No matching User."); ReadOnlyMemory ykLargeBlobKey = ykCredList[0].LargeBlobKey ?? throw new InvalidOperationException("No matching User."); - bool isValid = MemoryExtensions.SequenceEqual(targetKey.Span, ykLargeBlobKey.Span); + bool isValid = targetKey.Span.SequenceEqual(ykLargeBlobKey.Span); Assert.True(isValid); } } - [Fact] + [SkippableFact(typeof(DeviceNotFoundException))] public void DeleteCred_Succeeds() { _bioFido2Fixture.AddCredentials(1, 0); using (var fido2Session = new Fido2Session(_bioFido2Fixture.Device)) { fido2Session.KeyCollector = _bioFido2Fixture.KeyCollector; - fido2Session.AddPermissions(PinUvAuthTokenPermissions.AuthenticatorConfiguration, null); + fido2Session.AddPermissions(PinUvAuthTokenPermissions.AuthenticatorConfiguration); IReadOnlyList credList = fido2Session.EnumerateCredentialsForRelyingParty(_bioFido2Fixture.RpInfoList[2].RelyingParty); @@ -109,7 +110,7 @@ public void DeleteCred_Succeeds() Assert.Equal(1, count); fido2Session.ClearAuthToken(); - fido2Session.AddPermissions(PinUvAuthTokenPermissions.AuthenticatorConfiguration, null); + fido2Session.AddPermissions(PinUvAuthTokenPermissions.AuthenticatorConfiguration); fido2Session.DeleteCredential(credList[0].CredentialId); @@ -119,7 +120,7 @@ public void DeleteCred_Succeeds() } } - [Fact] + [SkippableFact(typeof(DeviceNotFoundException))] public void UpdateUserInfo_Succeeds() { string updatedDisplayName = "Updated Display Name"; @@ -127,14 +128,14 @@ public void UpdateUserInfo_Succeeds() using (var fido2Session = new Fido2Session(_bioFido2Fixture.Device)) { fido2Session.KeyCollector = _bioFido2Fixture.KeyCollector; - fido2Session.AddPermissions(PinUvAuthTokenPermissions.AuthenticatorConfiguration, null); + fido2Session.AddPermissions(PinUvAuthTokenPermissions.AuthenticatorConfiguration); IReadOnlyList credList = fido2Session.EnumerateCredentialsForRelyingParty(_bioFido2Fixture.RpInfoList[0].RelyingParty); Assert.NotEmpty(credList); fido2Session.ClearAuthToken(); - fido2Session.AddPermissions(PinUvAuthTokenPermissions.AuthenticatorConfiguration, null); + fido2Session.AddPermissions(PinUvAuthTokenPermissions.AuthenticatorConfiguration); UserEntity newInfo = credList[0].User; newInfo.DisplayName = updatedDisplayName; @@ -143,7 +144,7 @@ public void UpdateUserInfo_Succeeds() credList = fido2Session.EnumerateCredentialsForRelyingParty(_bioFido2Fixture.RpInfoList[0].RelyingParty); - string displayName = credList[0].User.DisplayName??""; + string displayName = credList[0].User.DisplayName ?? ""; Assert.Equal(updatedDisplayName, displayName); } } diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/GetAuthenticatorInfoTests.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/GetAuthenticatorInfoTests.cs index 627bacb6..1d36f6b9 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/GetAuthenticatorInfoTests.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/GetAuthenticatorInfoTests.cs @@ -20,6 +20,7 @@ namespace Yubico.YubiKey.Fido2 public class GetAuthenticatorInfoTests { [Fact] + [Trait("Category", "Simple")] public void GetAuthenticator_Succeeds() { IYubiKeyDevice yubiKey = YubiKeyDevice.FindAll().First(); diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/LargeBlobTests.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/LargeBlobTests.cs index 5f2a9796..afe6f9f3 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/LargeBlobTests.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/LargeBlobTests.cs @@ -15,11 +15,12 @@ using System; using System.Collections.Generic; using Xunit; -using Yubico.YubiKey.TestUtilities; using Yubico.YubiKey.Fido2.Commands; +using Yubico.YubiKey.TestUtilities; namespace Yubico.YubiKey.Fido2 { + [Trait("Category", "RequiresBio")] public class LargeBlobTests { static readonly byte[] _clientDataHash = { @@ -29,7 +30,7 @@ public class LargeBlobTests static readonly RelyingParty _rp = new RelyingParty("relyingparty1"); - private readonly byte[] _pin = new byte[] { + private readonly byte[] _pin = { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36 }; @@ -37,14 +38,14 @@ public class LargeBlobTests public LargeBlobTests() { - _testDevice = IntegrationTestDeviceEnumeration.GetTestDevice(StandardTestDevice.Bio); + _testDevice = IntegrationTestDeviceEnumeration.GetTestDevice(StandardTestDevice.Fw5Bio); } - //[Fact(Skip = "This test requires user interaction to reset the FIDO2 application.")] - [Fact] + //This test requires user interaction to reset the FIDO2 application. + [SkippableFact(typeof(DeviceNotFoundException))] public void SetLargeBlob_Succeeds() { - bool isValid = DoReset(_testDevice.SerialNumber); + bool isValid = Fido2ResetForTest.DoReset(_testDevice.SerialNumber); Assert.True(isValid); using (var fido2Session = new Fido2Session(_testDevice)) @@ -66,7 +67,7 @@ public void SetLargeBlob_Succeeds() mcParams1.AddExtension("largeBlobKey", new byte[] { 0xF5 }); mcParams1.AddOption(AuthenticatorOptions.rk, true); - fido2Session.AddPermissions(PinUvAuthTokenPermissions.AuthenticatorConfiguration, null); + fido2Session.AddPermissions(PinUvAuthTokenPermissions.AuthenticatorConfiguration); MakeCredentialData mcData1 = fido2Session.MakeCredential(mcParams1); Assert.True(mcData1.VerifyAttestation(_clientDataHash)); @@ -93,15 +94,15 @@ public void SetLargeBlob_Succeeds() Assert.Equal(2, assertions.Count); SerializedLargeBlobArray blobArray = fido2Session.GetSerializedLargeBlobArray(); - Assert.NotNull(blobArray.EncodedArray); + _ = Assert.NotNull(blobArray.EncodedArray); - byte[] blobData1 = new byte[] { + byte[] blobData1 = { 0x31, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50 }; - Assert.NotNull(mcData1.LargeBlobKey); + _ = Assert.NotNull(mcData1.LargeBlobKey); ReadOnlyMemory key1 = ReadOnlyMemory.Empty; if (!(mcData1.LargeBlobKey is null)) { @@ -110,13 +111,13 @@ public void SetLargeBlob_Succeeds() } Assert.Null(blobArray.Digest); - byte[] blobData2 = new byte[] { + byte[] blobData2 = { 0x32, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70 }; - Assert.NotNull(mcData2.LargeBlobKey); + _ = Assert.NotNull(mcData2.LargeBlobKey); ReadOnlyMemory key2 = ReadOnlyMemory.Empty; if (!(mcData2.LargeBlobKey is null)) { @@ -125,30 +126,22 @@ public void SetLargeBlob_Succeeds() } fido2Session.SetSerializedLargeBlobArray(blobArray); - Assert.NotNull(blobArray.Digest); + _ = Assert.NotNull(blobArray.Digest); blobArray = fido2Session.GetSerializedLargeBlobArray(); Assert.Equal(2, blobArray.Entries.Count); bool isDecrypted = blobArray.Entries[0].TryDecrypt(key1, out Memory plaintext1); Assert.True(isDecrypted); - isValid = MemoryExtensions.SequenceEqual(plaintext1.Span, blobData1.AsSpan()); + isValid = plaintext1.Span.SequenceEqual(blobData1.AsSpan()); Assert.True(isValid); isDecrypted = blobArray.Entries[1].TryDecrypt(key1, out Memory plaintext2); Assert.False(isDecrypted); isDecrypted = blobArray.Entries[1].TryDecrypt(key2, out plaintext2); Assert.True(isDecrypted); - isValid = MemoryExtensions.SequenceEqual(plaintext2.Span, blobData2.AsSpan()); + isValid = plaintext2.Span.SequenceEqual(blobData2.AsSpan()); Assert.True(isValid); } } - - private bool DoReset(int? serialNum) - { - var fido2Reset = new Fido2ResetForTest(serialNum); - ResponseStatus status = fido2Reset.RunFido2Reset(); - - return status == ResponseStatus.Success; - } } } diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/MakeCredentialBlobTests.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/MakeCredentialBlobTests.cs index fec79451..3ec796dc 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/MakeCredentialBlobTests.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/MakeCredentialBlobTests.cs @@ -32,13 +32,13 @@ public void CredBlobExtension_Correct() GetInfoResponse getInfoRsp = connection.SendCommand(getInfoCmd); Assert.Equal(ResponseStatus.Success, getInfoRsp.Status); AuthenticatorInfo authInfo = getInfoRsp.GetData(); - Assert.Equal(32, authInfo.MaximumCredentialBlobLength); + Assert.Equal(32, authInfo.MaximumCredentialBlobLength); /* Assert.Equal() Failure: Values differExpected: 32 Actual: null */ int maxCredBlobLength = authInfo.MaximumCredentialBlobLength ?? 0; Assert.NotNull(authInfo.Extensions); if (!(authInfo.Extensions is null)) { - bool isValid = authInfo.Extensions.Contains("credBlob") && (maxCredBlobLength > 0); + bool isValid = authInfo.Extensions.Contains("credBlob") && maxCredBlobLength > 0; Assert.True(isValid); } } @@ -57,18 +57,14 @@ public void MakeCredentialCommand_Succeeds() Assert.True(isValid); isValid = SupportsLargeBlobs(fido2Session.AuthenticatorInfo); - Assert.True(isValid); + Assert.True(isValid); /*Xunit.Sdk.TrueException +Assert.True() Failure +Expected: True +Actual: False*/ isValid = GetParams(fido2Session, out MakeCredentialParameters makeParams); Assert.True(isValid); } - -// var cmd = new MakeCredentialCommand(makeParams); -// MakeCredentialResponse rsp = connection.SendCommand(cmd); -// Assert.Equal(ResponseStatus.Success, rsp.Status); -// MakeCredentialData cData = rsp.GetData(); -// isValid = cData.VerifyAttestation(makeParams.ClientDataHash); -// Assert.True(isValid); } private bool SupportsLargeBlobs(AuthenticatorInfo authenticatorInfo) @@ -88,11 +84,13 @@ private bool GetParams( Fido2Session fido2Session, out MakeCredentialParameters makeParams) { - byte[] clientDataHash = new byte[] { + byte[] clientDataHash = + { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38 }; - byte[] arbitraryData = new byte[] { + byte[] arbitraryData = + { 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4A }; @@ -100,7 +98,7 @@ private bool GetParams( { Name = "SomeRpName", }; - byte[] userId = new byte[] { 0x11, 0x22, 0x33, 0x44 }; + byte[] userId = { 0x11, 0x22, 0x33, 0x44 }; var user = new UserEntity(new ReadOnlyMemory(userId)) { Name = "SomeUserName", @@ -113,7 +111,8 @@ private bool GetParams( { return false; } - ReadOnlyMemory token = (ReadOnlyMemory)fido2Session.AuthToken; + + var token = (ReadOnlyMemory)fido2Session.AuthToken; byte[] pinUvAuthParam = fido2Session.AuthProtocol.AuthenticateUsingPinToken( token.ToArray(), clientDataHash); diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/MakeCredentialGetAssertionTests.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/MakeCredentialGetAssertionTests.cs index d62334f8..4bccafff 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/MakeCredentialGetAssertionTests.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/MakeCredentialGetAssertionTests.cs @@ -17,6 +17,7 @@ using System.Linq; using System.Text; using Xunit; +using Yubico.YubiKey.TestUtilities; namespace Yubico.YubiKey.Fido2 { @@ -29,12 +30,15 @@ public class MakeCredentialGetAssertionTests static readonly RelyingParty _rp = new RelyingParty("relyingparty1"); - [Fact] + // This test requires user to touch the device. + [Fact, Trait("Category", "RequiresTouch")] public void MakeCredential_NonDiscoverable_GetAssertion_Succeeds() { - // Test assumptions: PIN is already set to 123456 (UTF-8 chars, not the number `123456`) IYubiKeyDevice yubiKeyDevice = YubiKeyDevice.FindByTransport(Transport.HidFido).First(); + bool isValid = Fido2ResetForTest.DoReset(yubiKeyDevice.SerialNumber); + Assert.True(isValid); + using (var fido2 = new Fido2Session(yubiKeyDevice)) { // Set up a key collector @@ -68,15 +72,27 @@ public void MakeCredential_NonDiscoverable_GetAssertion_Succeeds() GetAssertionData assertion = Assert.Single(assertions); Assert.Equal(1, assertion.NumberOfCredentials); + // Assert.Equal() Failure: Values differ + // Expected: 1 + // Actual: null + + // assertion.NumberOfCredentials + // The total number of credentials found on the YubiKey for the relying + // party. This is optional and can be null. If null, then there is only + // one credential. + // } } - [Fact] + // This test requires user to touch the device. + [Fact, Trait("Category", "RequiresTouch")] public void MakeCredential_NoName_GetAssertion_Succeeds() { - // Test assumptions: PIN is already set to 123456 (UTF-8 chars, not the number `123456`) IYubiKeyDevice yubiKeyDevice = YubiKeyDevice.FindByTransport(Transport.HidFido).First(); + bool isValid = Fido2ResetForTest.DoReset(yubiKeyDevice.SerialNumber); + Assert.True(isValid); + using (var fido2 = new Fido2Session(yubiKeyDevice)) { // Set up a key collector @@ -107,20 +123,23 @@ public void MakeCredential_NoName_GetAssertion_Succeeds() } } - [Fact] + // This test requires user to touch the device. + [Fact, Trait("Category", "RequiresTouch")] public void MakeCredential_MultipleCredentials_GetAssertion_ReturnsMultipleAssertions() { - // Test assumptions: PIN is already set to 123456 (UTF-8 chars, not the number `123456`) IYubiKeyDevice yubiKeyDevice = YubiKeyDevice.FindByTransport(Transport.HidFido).First(); + bool isValid = Fido2ResetForTest.DoReset(yubiKeyDevice.SerialNumber); + Assert.True(isValid); + using (var fido2 = new Fido2Session(yubiKeyDevice)) { // Set up a key collector fido2.KeyCollector = KeyCollector; - int startCount = (int)fido2.AuthenticatorInfo.RemainingDiscoverableCredentials!; + int startCount = (int)fido2.AuthenticatorInfo.RemainingDiscoverableCredentials!; //RemainingDiscoverableCredentials is NULL on my two keys I tried with (USBA 5.4.3 Keychain and Nano) // Verify the PIN - fido2.VerifyPin(); + fido2.VerifyPin(); //Never completes on my 5.7 // Call MakeCredential var user1 = new UserEntity(new byte[] { 1, 2, 3, 4 }) diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/MinPinLenTests.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/MinPinLenTests.cs index 273c3d9c..103fc6de 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/MinPinLenTests.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/MinPinLenTests.cs @@ -13,8 +13,8 @@ // limitations under the License. using System; -using System.Text; using System.Collections.Generic; +using System.Text; using Xunit; using Yubico.YubiKey.TestUtilities; @@ -37,11 +37,12 @@ public class MinPinLenTests : SimpleIntegrationTestConnection }; public MinPinLenTests() - : base(YubiKeyApplication.Fido2, StandardTestDevice.Fw5) + : base(YubiKeyApplication.Fido2) { } [Fact] + [Trait("Category", "Simple")] public void GetMinPinFromCredential_Succeeds() { using (var fido2Session = new Fido2Session(Device)) @@ -51,7 +52,7 @@ public void GetMinPinFromCredential_Succeeds() OptionValue ovMinPin = fido2Session.AuthenticatorInfo.GetOptionValue("setMinPINLength"); OptionValue ovCredMgmt = fido2Session.AuthenticatorInfo.GetOptionValue( AuthenticatorOptions.credMgmt); - if ((ovMinPin != OptionValue.True) || (ovCredMgmt != OptionValue.True) || !isSupported) + if (ovMinPin != OptionValue.True || ovCredMgmt != OptionValue.True || !isSupported) { return; } @@ -64,7 +65,7 @@ public void GetMinPinFromCredential_Succeeds() int? minPinLen = mcData!.AuthenticatorData.GetMinPinLengthExtension(); - Assert.NotNull(minPinLen); + _ = Assert.NotNull(minPinLen); DeleteAddedCredential(fido2Session); } @@ -78,7 +79,7 @@ private bool AddCredential(Fido2Session fido2Session, out MakeCredentialData? mc { _rp.Id }; - bool isSet = fido2Session.TrySetPinConfig(null, rpList, null); + bool isSet = fido2Session.TrySetPinConfig(null, rpList); if (!isSet) { return false; diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/NoSerialNumberTests.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/NoSerialNumberTests.cs index a7577e08..6f80fd11 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/NoSerialNumberTests.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/NoSerialNumberTests.cs @@ -21,6 +21,7 @@ namespace Yubico.YubiKey.Fido2 public class NoSerialNumberTests { [Fact] + [Trait("Category", "Simple")] public void GetTestDevice_NoSerialNumber_Succeeds() { IYubiKeyDevice device = IntegrationTestDeviceEnumeration.GetTestDevice(StandardTestDevice.Fw5, false); diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/PinCollectionTests.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/PinCollectionTests.cs index 111eaccc..132f4cff 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/PinCollectionTests.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/PinCollectionTests.cs @@ -23,6 +23,7 @@ namespace Yubico.YubiKey.Fido2 public class PinCollectionTests { [Fact] + [Trait("Category", "RequiresSetup")] public void PinOperations_Succeed() { // Assumption - the YubiKey returned has a new or reset FIDO2 application with no PIN set. @@ -82,6 +83,7 @@ public void PinOperations_Succeed() } [Fact] + [Trait("Category", "RequiresSetup")] public void UvOperations_Succeed() { // Test assumptions: PIN is already set to 123456 (UTF-8 chars, not the number `123456`) @@ -97,6 +99,7 @@ public void UvOperations_Succeed() } [Fact] + [Trait("Category", "RequiresSetup")] public void InvalidPinFollowedByValidPin_Succeeds() { // Test assumption: PIN is already set to 123456 (UTF-8 chars, not the number `123456`) diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/SimpleCredMgmtTests.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/SimpleCredMgmtTests.cs index 65f27212..56bb51cc 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/SimpleCredMgmtTests.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/SimpleCredMgmtTests.cs @@ -13,17 +13,18 @@ // limitations under the License. using System; -using System.Text; using System.Collections.Generic; +using System.Text; using Xunit; using Yubico.YubiKey.TestUtilities; namespace Yubico.YubiKey.Fido2 { + [Trait("Category", "FirmwareOrHardwareMissmatch")] public class SimpleCredMgmtTests : SimpleIntegrationTestConnection { public SimpleCredMgmtTests() - : base(YubiKeyApplication.Fido2, StandardTestDevice.Fw5) + : base(YubiKeyApplication.Fido2) { } @@ -35,7 +36,10 @@ public void GetMetadata_Succeeds() fido2Session.KeyCollector = LocalKeyCollector; (int credCount, int slotCount) = fido2Session.GetCredentialMetadata(); - Assert.Equal(1, credCount); + Assert.Equal(1, credCount); /*Xunit.Sdk.EqualException +Assert.Equal() Failure: Values differ +Expected: 1 +Actual: 0*/ Assert.Equal(24, slotCount); } } @@ -48,12 +52,12 @@ public void EnumerateRps_Succeeds() fido2Session.KeyCollector = LocalKeyCollector; IReadOnlyList rpList = fido2Session.EnumerateRelyingParties(); - Assert.Equal(2, rpList.Count); + Assert.Equal(2, rpList.Count); //Failing test Yubico.YubiKey.Fido2.Ctap2DataException: The FIDO2 info returned is invalid. } } [Fact] - public void EnumerateCreds_Succeeds() + public void EnumerateCreds_Succeeds() // Failing test, Yubico.YubiKey.Fido2.Ctap2DataException: The FIDO2 info returned is invalid. { using (var fido2Session = new Fido2Session(Device)) { diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/VerifyFpTests.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/VerifyFpTests.cs index 0ce78918..4af51eec 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/VerifyFpTests.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Fido2/VerifyFpTests.cs @@ -14,21 +14,21 @@ using System; using System.Text; -using System.Collections.Generic; using Xunit; using Yubico.YubiKey.Fido2.Commands; using Yubico.YubiKey.TestUtilities; namespace Yubico.YubiKey.Fido2 { + [Trait("Category", "RequiresBio")] public class VerifyFpTests : SimpleIntegrationTestConnection { public VerifyFpTests() - : base(YubiKeyApplication.Fido2, StandardTestDevice.Bio) + : base(YubiKeyApplication.Fido2, StandardTestDevice.Fw5Bio) { } - [Fact] + [SkippableFact(typeof(DeviceNotFoundException))] public void VerifyUv_Succeeds() { using (var fido2Session = new Fido2Session(Device)) diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/HasFidoFeatureTests.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/HasFidoFeatureTests.cs index 6eb66e71..e78df759 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/HasFidoFeatureTests.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/HasFidoFeatureTests.cs @@ -14,6 +14,7 @@ using System.Linq; using Xunit; +using Yubico.YubiKey.TestUtilities; namespace Yubico.YubiKey { @@ -22,20 +23,21 @@ public class HasFidoFeatureTests [Fact] public void HasFeature_ApplicationOTP_Correct() { - IYubiKeyDevice yubiKeyDevice = YubiKeyDevice.FindByTransport(Transport.All).First(); - bool expectedResult = yubiKeyDevice.IsSkySeries ? false : true; + IYubiKeyDevice yubiKeyDevice = YubiKeyDevice.FindByTransport().First(); bool hasFeature = yubiKeyDevice.HasFeature(YubiKeyFeature.OtpApplication); - + bool expectedResult = !yubiKeyDevice.IsSkySeries; Assert.Equal(hasFeature, expectedResult); } [Fact] public void HasFeature_ApplicationU2F_Correct() { - IYubiKeyDevice yubiKeyDevice = TestUtilities.IntegrationTestDeviceEnumeration.GetTestDevices().First(); + IYubiKeyDevice yubiKeyDevice = IntegrationTestDeviceEnumeration.GetTestDevices().First(); bool expectedResult = true; - if (!yubiKeyDevice.IsSkySeries && (yubiKeyDevice.FirmwareVersion.Major < 3)) + + //Can this be removed? + if (!yubiKeyDevice.IsSkySeries && yubiKeyDevice.FirmwareVersion.Major < 3) { expectedResult = false; } @@ -48,9 +50,9 @@ public void HasFeature_ApplicationU2F_Correct() [Fact] public void HasFeature_ApplicationFido2_Correct() { - IYubiKeyDevice yubiKeyDevice = TestUtilities.IntegrationTestDeviceEnumeration.GetTestDevices().First(); + IYubiKeyDevice yubiKeyDevice = IntegrationTestDeviceEnumeration.GetTestDevices().First(); bool expectedResult = true; - if (!yubiKeyDevice.IsSkySeries && (yubiKeyDevice.FirmwareVersion.Major < 5)) + if (!yubiKeyDevice.IsSkySeries && yubiKeyDevice.FirmwareVersion.Major < 5) { expectedResult = false; } diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Management/SetDeviceInfoCommandTests.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Management/SetDeviceInfoCommandTests.cs index 7bba047c..95c8aa6a 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Management/SetDeviceInfoCommandTests.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Management/SetDeviceInfoCommandTests.cs @@ -12,15 +12,16 @@ // See the License for the specific language governing permissions and // limitations under the License. +using Xunit; using Yubico.YubiKey.Management.Commands; using Yubico.YubiKey.TestUtilities; -using Xunit; namespace Yubico.YubiKey.Management { + [Trait("Category", "Simple")] public class SetDeviceInfoCommandTests { - [Theory] + [SkippableTheory(typeof(DeviceNotFoundException))] [InlineData(StandardTestDevice.Fw5)] [InlineData(StandardTestDevice.Fw5Fips)] public void SetDeviceInfo_NoData_ResponseStatusSuccess(StandardTestDevice testDeviceType) @@ -35,7 +36,7 @@ public void SetDeviceInfo_NoData_ResponseStatusSuccess(StandardTestDevice testDe Assert.Equal(ResponseStatus.Success, setDeviceInfoResponse.Status); } - [Theory] + [SkippableTheory(typeof(DeviceNotFoundException))] [InlineData(StandardTestDevice.Fw5)] [InlineData(StandardTestDevice.Fw5Fips)] public void SetDeviceInfo_NoChanges_DeviceInfoNotChanged(StandardTestDevice testDeviceType) @@ -52,13 +53,13 @@ public void SetDeviceInfo_NoChanges_DeviceInfoNotChanged(StandardTestDevice test Assert.Equal(ResponseStatus.Success, setDeviceInfoResponse.Status); } - IYubiKeyDevice endingTestDevice = + IYubiKeyDevice endingTestDevice = TestDeviceSelection.RenewDeviceEnumeration(testDeviceSerialNumber); AssertDeviceInfoValueEquals(beginningTestDevice, endingTestDevice); } - [Theory] + [SkippableTheory(typeof(DeviceNotFoundException))] [InlineData(StandardTestDevice.Fw5)] [InlineData(StandardTestDevice.Fw5Fips)] public void SetDeviceInfo_SameAsCurrentDeviceInfo_NoChange(StandardTestDevice testDeviceType) @@ -102,7 +103,8 @@ private static void AssertDeviceInfoValueEquals( } private static SetDeviceInfoCommand CreateSetDeviceInfoCommand(IYubiKeyDeviceInfo deviceInfo) => - new SetDeviceInfoCommand { + new SetDeviceInfoCommand + { EnabledUsbCapabilities = deviceInfo.EnabledUsbCapabilities, EnabledNfcCapabilities = deviceInfo.EnabledNfcCapabilities, ChallengeResponseTimeout = deviceInfo.ChallengeResponseTimeout, diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Oath/CredentialFixture.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Oath/CredentialFixture.cs index 9d3a63b8..d552d107 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Oath/CredentialFixture.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Oath/CredentialFixture.cs @@ -14,7 +14,7 @@ namespace Yubico.YubiKey.Oath { - public class CredentialFixture + public class CredentialFixture { public Credential TotpCredential { get; private set; } @@ -30,7 +30,8 @@ public class CredentialFixture public CredentialFixture() { - TotpCredential = new Credential { + TotpCredential = new Credential + { Issuer = "Microsoft", AccountName = "test@outlook.com", Type = CredentialType.Totp, diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Oath/CredentialTests.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Oath/CredentialTests.cs index 46d1a85d..ca78003d 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Oath/CredentialTests.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Oath/CredentialTests.cs @@ -14,11 +14,12 @@ using System.Collections.Generic; using Xunit; -using Yubico.YubiKey.TestUtilities; using Yubico.YubiKey.Oath.Commands; +using Yubico.YubiKey.TestUtilities; namespace Yubico.YubiKey.Oath { + [Trait("Category", "Simple")] [TestCaseOrderer(PriorityOrderer.TypeName, PriorityOrderer.AssembyName)] public class CredentialTests : IClassFixture { @@ -104,10 +105,10 @@ public void RenameCredential_Totp(StandardTestDevice testDeviceType) IYubiKeyDevice testDevice = IntegrationTestDeviceEnumeration.GetTestDevice(testDeviceType); using IYubiKeyConnection connection = testDevice.Connect(YubiKeyApplication.Oath); - - var renameCommand = new RenameCommand(_fixture.TotpCredential, "Test", "test@example.com"); + + var renameCommand = new RenameCommand(_fixture.TotpCredential, "Test", "test@example.com"); OathResponse response = connection.SendCommand(renameCommand); - + Assert.Equal(ResponseStatus.Success, response.Status); } @@ -138,7 +139,7 @@ public void DeleteCredential_Totp(StandardTestDevice testDeviceType) _fixture.TotpCredential.Issuer = ""; _fixture.TotpCredential.AccountName = "test@example.com"; - + DeleteResponse response = connection.SendCommand(new DeleteCommand(_fixture.TotpCredential)); Assert.Equal(ResponseStatus.Success, response.Status); } diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Oath/GetLargeData.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Oath/GetLargeData.cs index 19cf072f..e52691be 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Oath/GetLargeData.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Oath/GetLargeData.cs @@ -24,11 +24,12 @@ namespace Yubico.YubiKey.Oath // retrieve large amounts of data that spans more // than one APDU. For more information, see // Pipelines.ResponseChainingTransform. + [Trait("Category", "Simple")] public sealed class GetLargeData { private static readonly Random random = new Random(); - public static string RandomString(int length) + private static string RandomString(int length) { const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; return new string(Enumerable.Repeat(chars, length) @@ -65,7 +66,7 @@ private IYubiKeyDevice GetCleanDevice(StandardTestDevice testDeviceType) public void GetLotsOfCredentials(StandardTestDevice testDeviceType) { IYubiKeyDevice testDevice = GetCleanDevice(testDeviceType); - var expectedCredsOnDevice = FillWithRandCreds(testDevice); + IEnumerable? expectedCredsOnDevice = FillWithRandCreds(testDevice); IEnumerable actualCredsOnDevice; using (var oathSession = new OathSession(testDevice)) diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Oath/NoCollectorPasswordTests.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Oath/NoCollectorPasswordTests.cs index 9ae3005c..dca64dbe 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Oath/NoCollectorPasswordTests.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Oath/NoCollectorPasswordTests.cs @@ -13,14 +13,13 @@ // limitations under the License. using System; -using System.Collections; using System.Collections.Generic; using Xunit; using Yubico.YubiKey.TestUtilities; -using Yubico.YubiKey.Oath.Commands; namespace Yubico.YubiKey.Oath { + [Trait("Category", "Simple")] public sealed class NoCollectorPasswordTests { [Fact] diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Oath/OathSessionCredentialTests.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Oath/OathSessionCredentialTests.cs index 543b4ffb..3d0b1402 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Oath/OathSessionCredentialTests.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Oath/OathSessionCredentialTests.cs @@ -20,6 +20,7 @@ namespace Yubico.YubiKey.Oath { [TestCaseOrderer(PriorityOrderer.TypeName, PriorityOrderer.AssembyName)] + [Trait("Category", "Simple")] public sealed class OathSessionCredentialTests : IClassFixture { // Shared object instance across tests. @@ -99,8 +100,8 @@ public void CalculateTotpCredential(StandardTestDevice testDeviceType) Code data = oathSession.CalculateCredential(_fixture.TotpCredentialWithDefaultPeriod); Assert.NotNull(data.Value); - Assert.NotNull(data.ValidFrom); - Assert.NotNull(data.ValidUntil); + _ = Assert.NotNull(data.ValidFrom); + _ = Assert.NotNull(data.ValidUntil); int difference = (int)(data.ValidUntil! - data.ValidFrom!).Value.TotalSeconds; @@ -122,8 +123,8 @@ public void CalculateHotpCredential(StandardTestDevice testDeviceType) Code data = oathSession.CalculateCredential(_fixture.HotpCredential); Assert.NotNull(data.Value); - Assert.NotNull(data.ValidFrom); - Assert.NotNull(data.ValidUntil); + _ = Assert.NotNull(data.ValidFrom); + _ = Assert.NotNull(data.ValidUntil); Assert.Equal(DateTimeOffset.MaxValue, data.ValidUntil); } } @@ -146,8 +147,8 @@ public void CalculateTotpCredentialUsingParameters(StandardTestDevice testDevice CredentialPeriod.Period15); Assert.NotNull(data.Value); - Assert.NotNull(data.ValidFrom); - Assert.NotNull(data.ValidUntil); + _ = Assert.NotNull(data.ValidFrom); + _ = Assert.NotNull(data.ValidUntil); int difference = (int)(data.ValidUntil! - data.ValidFrom!).Value.TotalSeconds; @@ -173,8 +174,8 @@ public void CalculateHotpCredentialUsingParameters(StandardTestDevice testDevice 0); Assert.NotNull(data.Value); - Assert.NotNull(data.ValidFrom); - Assert.NotNull(data.ValidUntil); + _ = Assert.NotNull(data.ValidFrom); + _ = Assert.NotNull(data.ValidUntil); Assert.Equal(DateTimeOffset.MaxValue, data.ValidUntil); } } @@ -330,11 +331,11 @@ public void AddInvalidCredential_ThrowsException(StandardTestDevice testDeviceTy var collectorObj = new SimpleOathKeyCollector(); oathSession.KeyCollector = collectorObj.SimpleKeyCollectorDelegate; + //Why should this fail? _ = Assert.Throws(() => oathSession.AddCredential( "GitHub", "test@gmail.com", - CredentialType.Hotp, - CredentialPeriod.Period30)); + CredentialType.Hotp)); } } diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Oath/OathSessionPasswordTests.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Oath/OathSessionPasswordTests.cs index 233f8d75..e8a212e2 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Oath/OathSessionPasswordTests.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Oath/OathSessionPasswordTests.cs @@ -18,6 +18,7 @@ namespace Yubico.YubiKey.Oath { [TestCaseOrderer(PriorityOrderer.TypeName, PriorityOrderer.AssembyName)] + [Trait("Category", "Simple")] public sealed class OathSessionPasswordTests { [Theory, TestPriority(0)] diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Oath/SelectApplicationTests.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Oath/SelectApplicationTests.cs index 63d718d8..60c969f2 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Oath/SelectApplicationTests.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Oath/SelectApplicationTests.cs @@ -12,14 +12,15 @@ // See the License for the specific language governing permissions and // limitations under the License. -using Yubico.YubiKey.TestUtilities; using Xunit; +using Yubico.YubiKey.TestUtilities; namespace Yubico.YubiKey.Oath { + [Trait("Category", "Simple")] public sealed class SelectApplicationTests { - [Theory] + [SkippableTheory(typeof(DeviceNotFoundException))] [InlineData(StandardTestDevice.Fw5)] public void ConnectOathHasData(StandardTestDevice testDeviceType) { diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Otp/ConfigureStaticTests.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Otp/ConfigureStaticTests.cs index d37e9f00..2a6b7c87 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Otp/ConfigureStaticTests.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Otp/ConfigureStaticTests.cs @@ -13,16 +13,18 @@ // limitations under the License. using System; +using Xunit; using Yubico.Core.Devices.Hid; -using Yubico.YubiKey.TestUtilities; using Yubico.YubiKey.Otp.Operations; -using Xunit; +using Yubico.YubiKey.TestUtilities; namespace Yubico.YubiKey.Otp { public class ConfigureStaticTests { - [Theory] + + [Trait("Category", "Simple")] + [SkippableTheory(typeof(DeviceNotFoundException))] [InlineData(StandardTestDevice.Fw5)] [InlineData(StandardTestDevice.Fw5Fips)] public void ConfigureStaticPassword_Succeeds(StandardTestDevice testDeviceType) @@ -45,7 +47,7 @@ public void ConfigureStaticPassword_Succeeds(StandardTestDevice testDeviceType) configObj = configObj.AllowManualUpdate(false); configObj = configObj.AppendCarriageReturn(false); configObj = configObj.SendTabFirst(false); - configObj = configObj.SetAllowUpdate(true); + configObj = configObj.SetAllowUpdate(); configObj = configObj.GeneratePassword(generatedPassword); configObj.Execute(); } diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Otp/ListenHidTests.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Otp/ListenHidTests.cs index 8e995921..36818d1a 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Otp/ListenHidTests.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Otp/ListenHidTests.cs @@ -12,12 +12,13 @@ // See the License for the specific language governing permissions and // limitations under the License. -using Yubico.Core.Devices.Hid; using Xunit; using Xunit.Abstractions; +using Yubico.Core.Devices.Hid; namespace Yubico.PlatformInterop { + [Trait("Category", "Simple")] public class ListenHidTests { private int _counter; @@ -57,7 +58,7 @@ private int RunMenu() { _counter = 6; } - else if ((_counter > 6) || (_counter < 0)) + else if (_counter > 6 || _counter < 0) { _counter = 1; } diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Otp/ListenSmartCardTests.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Otp/ListenSmartCardTests.cs index 9b823a2d..03cfd75f 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Otp/ListenSmartCardTests.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Otp/ListenSmartCardTests.cs @@ -18,6 +18,7 @@ namespace Yubico.PlatformInterop { + [Trait("Category", "Simple")] public class ListenSmartCardTests { private int _counter; @@ -57,7 +58,7 @@ private int RunMenu() { _counter = 6; } - else if ((_counter > 6) || (_counter < 0)) + else if (_counter > 6 || _counter < 0) { _counter = 1; } diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/AesMgmtKeyTests.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/AesMgmtKeyTests.cs index 96a4b42d..e41cd161 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/AesMgmtKeyTests.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/AesMgmtKeyTests.cs @@ -14,26 +14,27 @@ using System; using System.Security.Cryptography; -using Yubico.YubiKey.TestUtilities; -using Yubico.YubiKey.Piv.Commands; using Xunit; +using Yubico.YubiKey.TestUtilities; namespace Yubico.YubiKey.Piv { + [Trait("Category", "Simple")] public class AesMgmtKeyTests : IDisposable { - private readonly bool _runTest = false; - private readonly IYubiKeyDevice _yubiKey; + private readonly Memory _currentKey; private readonly byte[] _currentKeyBytes; + private readonly Memory _newKey; private readonly byte[] _newKeyBytes; + private readonly bool _runTest; + private readonly IYubiKeyDevice _yubiKey; private int _currentKeyLength; private int _newKeyLength; - private readonly Memory _currentKey; - private readonly Memory _newKey; - public AesMgmtKeyTests () + public AesMgmtKeyTests() { - _currentKeyBytes = new byte[] { + _currentKeyBytes = 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, @@ -84,8 +85,8 @@ public void ChangeMgmtKey_Auth_Succeeds(PivAlgorithm algorithm, int keySize, boo return; } - AuthenticateManagementKeyResult expectedResult = mutualAuth ? - AuthenticateManagementKeyResult.MutualFullyAuthenticated + AuthenticateManagementKeyResult expectedResult = mutualAuth + ? AuthenticateManagementKeyResult.MutualFullyAuthenticated : AuthenticateManagementKeyResult.SingleAuthenticated; SetKeyLengths(24, keySize); @@ -111,19 +112,20 @@ public void ChangeMgmtKey_Auth_Succeeds(PivAlgorithm algorithm, int keySize, boo // The Change call will always use mutual auth. Assert.True(pivSession.ManagementKeyAuthenticated); - Assert.Equal(AuthenticateManagementKeyResult.MutualFullyAuthenticated, pivSession.ManagementKeyAuthenticationResult); + Assert.Equal(AuthenticateManagementKeyResult.MutualFullyAuthenticated, + pivSession.ManagementKeyAuthenticationResult); Assert.Equal(algorithm, pivSession.ManagementKeyAlgorithm); // start temp -// pivSession.AuthenticateManagementKey(mutualAuth); -// -// var setCmd = new SetManagementKeyCommand( -// _newKey.Slice(0, keySize), PivTouchPolicy.Never, algorithm); -// -// SetManagementKeyResponse setRsp = pivSession.Connection.SendCommand(setCmd); -// Assert.Equal(ResponseStatus.Success, setRsp.Status); -// Assert.True(pivSession.ManagementKeyAuthenticated); -// Assert.Equal(expectedResult, pivSession.ManagementKeyAuthenticationResult); + // pivSession.AuthenticateManagementKey(mutualAuth); + // + // var setCmd = new SetManagementKeyCommand( + // _newKey.Slice(0, keySize), PivTouchPolicy.Never, algorithm); + // + // SetManagementKeyResponse setRsp = pivSession.Connection.SendCommand(setCmd); + // Assert.Equal(ResponseStatus.Success, setRsp.Status); + // Assert.True(pivSession.ManagementKeyAuthenticated); + // Assert.Equal(expectedResult, pivSession.ManagementKeyAuthenticationResult); // end temp SwapKeys(); @@ -158,8 +160,8 @@ public void ChangeMgmtKey_TryAuth_Succeeds(PivAlgorithm algorithm, int keySize, return; } - AuthenticateManagementKeyResult expectedResult = mutualAuth ? - AuthenticateManagementKeyResult.MutualFullyAuthenticated + AuthenticateManagementKeyResult expectedResult = mutualAuth + ? AuthenticateManagementKeyResult.MutualFullyAuthenticated : AuthenticateManagementKeyResult.SingleAuthenticated; SetKeyLengths(24, keySize); @@ -187,7 +189,8 @@ public void ChangeMgmtKey_TryAuth_Succeeds(PivAlgorithm algorithm, int keySize, // The Change call will always use mutual auth. Assert.True(pivSession.ManagementKeyAuthenticated); - Assert.Equal(AuthenticateManagementKeyResult.MutualFullyAuthenticated, pivSession.ManagementKeyAuthenticationResult); + Assert.Equal(AuthenticateManagementKeyResult.MutualFullyAuthenticated, + pivSession.ManagementKeyAuthenticationResult); Assert.Equal(algorithm, pivSession.ManagementKeyAlgorithm); SwapKeys(); @@ -223,8 +226,8 @@ public void ChangeMgmtKey_TryAuthNoColl_Succeeds(PivAlgorithm algorithm, int key return; } - AuthenticateManagementKeyResult expectedResult = mutualAuth ? - AuthenticateManagementKeyResult.MutualFullyAuthenticated + AuthenticateManagementKeyResult expectedResult = mutualAuth + ? AuthenticateManagementKeyResult.MutualFullyAuthenticated : AuthenticateManagementKeyResult.SingleAuthenticated; SetKeyLengths(24, keySize); @@ -233,7 +236,8 @@ public void ChangeMgmtKey_TryAuthNoColl_Succeeds(PivAlgorithm algorithm, int key Assert.False(pivSession.ManagementKeyAuthenticated); Assert.Equal(PivAlgorithm.TripleDes, pivSession.ManagementKeyAlgorithm); - bool isValid = pivSession.TryAuthenticateManagementKey(_currentKey.Slice(0, _currentKeyLength), mutualAuth); + bool isValid = + pivSession.TryAuthenticateManagementKey(_currentKey.Slice(0, _currentKeyLength), mutualAuth); Assert.True(isValid); Assert.True(pivSession.ManagementKeyAuthenticated); Assert.Equal(expectedResult, pivSession.ManagementKeyAuthenticationResult); @@ -254,7 +258,8 @@ public void ChangeMgmtKey_TryAuthNoColl_Succeeds(PivAlgorithm algorithm, int key // The Change call will always use mutual auth. Assert.True(pivSession.ManagementKeyAuthenticated); - Assert.Equal(AuthenticateManagementKeyResult.MutualFullyAuthenticated, pivSession.ManagementKeyAuthenticationResult); + Assert.Equal(AuthenticateManagementKeyResult.MutualFullyAuthenticated, + pivSession.ManagementKeyAuthenticationResult); Assert.Equal(algorithm, pivSession.ManagementKeyAlgorithm); SwapKeys(); @@ -266,7 +271,8 @@ public void ChangeMgmtKey_TryAuthNoColl_Succeeds(PivAlgorithm algorithm, int key Assert.False(pivSession.ManagementKeyAuthenticated); Assert.Equal(algorithm, pivSession.ManagementKeyAlgorithm); - bool isValid = pivSession.TryAuthenticateManagementKey(_currentKey.Slice(0, _currentKeyLength), mutualAuth); + bool isValid = + pivSession.TryAuthenticateManagementKey(_currentKey.Slice(0, _currentKeyLength), mutualAuth); Assert.True(isValid); Assert.True(pivSession.ManagementKeyAuthenticated); Assert.Equal(expectedResult, pivSession.ManagementKeyAuthenticationResult); @@ -281,7 +287,7 @@ public bool AesMgmtKeyTestsKeyCollectorDelegate(KeyEntryData keyEntryData) return false; } - if (keyEntryData.IsRetry == true) + if (keyEntryData.IsRetry) { return false; } diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/AttestTests.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/AttestTests.cs index ace91310..7a88eda1 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/AttestTests.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/AttestTests.cs @@ -14,13 +14,14 @@ using System; using System.Security.Cryptography.X509Certificates; -using Yubico.YubiKey.TestUtilities; -using Yubico.YubiKey.Piv.Commands; -using Yubico.Core.Tlv; using Xunit; +using Yubico.Core.Tlv; +using Yubico.YubiKey.Piv.Commands; +using Yubico.YubiKey.TestUtilities; namespace Yubico.YubiKey.Piv { + [Trait("Category", "Simple")] public class AttestTests { [Theory] @@ -77,7 +78,7 @@ public void Attest_Imported_ThrowsException(StandardTestDevice testDeviceType) [InlineData(PivAlgorithm.EccP384, StandardTestDevice.Fw5)] public void AttestGenerated(PivAlgorithm algorithm, StandardTestDevice testDeviceType) { - byte[] slotNumbers = new byte[] { + byte[] slotNumbers = { 0x9A, 0x9C, 0x9D, 0x9E, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8A, 0x8B, 0x8C, 0x8D, 0x8E, 0x8F, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95 @@ -199,7 +200,7 @@ private static bool AttestationShouldFail(int whichPair, IYubiKeyDevice testDevi } // version 4 YubiKeys accept 1024-bit RSA keys, so don't test that. - if ((testDevice.FirmwareVersion.Major < 5) && (whichPair == BadAttestationPairs.KeyRsa1024CertValid)) + if (testDevice.FirmwareVersion.Major < 5 && whichPair == BadAttestationPairs.KeyRsa1024CertValid) { return true; } diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/AuthTests.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/AuthTests.cs index 0186df43..34a93105 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/AuthTests.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/AuthTests.cs @@ -13,8 +13,8 @@ // limitations under the License. using System.Security; -using Yubico.YubiKey.TestUtilities; using Xunit; +using Yubico.YubiKey.TestUtilities; namespace Yubico.YubiKey.Piv { diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/CertSizeTests.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/CertSizeTests.cs index f1730878..c25f3b3f 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/CertSizeTests.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/CertSizeTests.cs @@ -15,20 +15,14 @@ using System; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; -using Yubico.YubiKey.TestUtilities; using Xunit; +using Yubico.YubiKey.TestUtilities; namespace Yubico.YubiKey.Piv { + [Trait("Category", "Simple")] public class CertSizeTests { - // private readonly ITestOutputHelper _output; - // - // public CertSizeTests (ITestOutputHelper output) - // { - // _output = output; - // } - [Theory] [InlineData(StandardTestDevice.Fw5)] public void SingleCertSize_3052(StandardTestDevice testDeviceType) @@ -51,7 +45,7 @@ public void SingleCertSize_3052(StandardTestDevice testDeviceType) rng.GetBytes(extensionData, 0, extensionData.Length); X509Certificate2 newCert = GetCertWithRandomExtension(caCert, dotNetPublicKey, extensionData); -// _output.WriteLine ("cert size: {0} from extension = {1}", newCert.RawData.Length, extensionSize); + // _output.WriteLine ("cert size: {0} from extension = {1}", newCert.RawData.Length, extensionSize); // A 3052-byte cert should work. using (var pivSession = new PivSession(testDevice)) @@ -71,7 +65,7 @@ public void SingleCertSize_3052(StandardTestDevice testDeviceType) rng.GetBytes(extensionData, 0, extensionData.Length); newCert = GetCertWithRandomExtension(caCert, dotNetPublicKey, extensionData); -// _output.WriteLine ("cert size: {0} from extension = {1}", newCert.RawData.Length, extensionSize); + // _output.WriteLine ("cert size: {0} from extension = {1}", newCert.RawData.Length, extensionSize); // A 3053-byte cert should throw an exception. using (var pivSession = new PivSession(testDevice)) @@ -121,7 +115,7 @@ public void MultipleCerts_3052(StandardTestDevice testDeviceType) { pivSession.ImportPrivateKey(leafSlotNumber, pivPrivateKey); pivSession.ImportCertificate(leafSlotNumber, newCert); -// _output.WriteLine ("slot number: {0:X2}", (int)leafSlotNumber & 0xFF); + // _output.WriteLine ("slot number: {0:X2}", (int)leafSlotNumber & 0xFF); } // The next storage should fail. @@ -151,7 +145,7 @@ public void AllSlot_2079(StandardTestDevice testDeviceType) rng.GetBytes(extensionData, 0, extensionData.Length); X509Certificate2 newCert = GetCertWithRandomExtension(caCert, dotNetPublicKey, extensionData); -// _output.WriteLine ("cert size: {0} from extension = {1}", newCert.RawData.Length, extensionSize); + // _output.WriteLine ("cert size: {0} from extension = {1}", newCert.RawData.Length, extensionSize); using (var pivSession = new PivSession(testDevice)) { @@ -167,28 +161,28 @@ public void AllSlot_2079(StandardTestDevice testDeviceType) { pivSession.ImportPrivateKey(leafSlotNumber, pivPrivateKey); pivSession.ImportCertificate(leafSlotNumber, newCert); -// _output.WriteLine ("slot number: {0:X2}", (int)leafSlotNumber & 0xFF); + // _output.WriteLine ("slot number: {0:X2}", (int)leafSlotNumber & 0xFF); } leafSlotNumber = 0x9A; pivSession.ImportPrivateKey(leafSlotNumber, pivPrivateKey); pivSession.ImportCertificate(leafSlotNumber, newCert); -// _output.WriteLine ("slot number: {0:X2}", (int)leafSlotNumber & 0xFF); + // _output.WriteLine ("slot number: {0:X2}", (int)leafSlotNumber & 0xFF); leafSlotNumber = 0x9C; pivSession.ImportPrivateKey(leafSlotNumber, pivPrivateKey); pivSession.ImportCertificate(leafSlotNumber, newCert); -// _output.WriteLine ("slot number: {0:X2}", (int)leafSlotNumber & 0xFF); + // _output.WriteLine ("slot number: {0:X2}", (int)leafSlotNumber & 0xFF); leafSlotNumber = 0x9D; pivSession.ImportPrivateKey(leafSlotNumber, pivPrivateKey); pivSession.ImportCertificate(leafSlotNumber, newCert); -// _output.WriteLine ("slot number: {0:X2}", (int)leafSlotNumber & 0xFF); + // _output.WriteLine ("slot number: {0:X2}", (int)leafSlotNumber & 0xFF); leafSlotNumber = 0x9E; pivSession.ImportPrivateKey(leafSlotNumber, pivPrivateKey); pivSession.ImportCertificate(leafSlotNumber, newCert); -// _output.WriteLine ("slot number: {0:X2}", (int)leafSlotNumber & 0xFF); + // _output.WriteLine ("slot number: {0:X2}", (int)leafSlotNumber & 0xFF); } } @@ -216,7 +210,7 @@ private static X509Certificate2 GetCertWithRandomExtension( DateTimeOffset notBefore = DateTimeOffset.Now; DateTimeOffset notAfter = notBefore.AddYears(1); - byte[] serialNumber = new byte[] { 0x02, 0x4A }; + byte[] serialNumber = { 0x02, 0x4A }; X509Certificate2 newCert = certRequest.Create( caCert, @@ -238,7 +232,7 @@ private static X509Certificate2 GetCACert() X509Certificate2 certObj = cert.GetCertObject(); var privateKey = new KeyConverter(privateKeyPem.ToCharArray()); RSA dotnetObj = privateKey.GetRsaObject(); - X509Certificate2 certCopy = RSACertificateExtensions.CopyWithPrivateKey(certObj, dotnetObj); + X509Certificate2 certCopy = certObj.CopyWithPrivateKey(dotnetObj); return certCopy; } diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/CertTests.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/CertTests.cs index 790a9946..ad2880ce 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/CertTests.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/CertTests.cs @@ -14,14 +14,15 @@ using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; +using Xunit; using Yubico.YubiKey.Piv.Commands; using Yubico.YubiKey.TestUtilities; -using Xunit; namespace Yubico.YubiKey.Piv { public class CertTests { + [Trait("Category", "Simple")] [Theory] [InlineData(StandardTestDevice.Fw5)] public void GetCert_Succeeds(StandardTestDevice testDeviceType) @@ -66,7 +67,7 @@ public void GetCert_NoAuth_Succeeds(StandardTestDevice testDeviceType) byte slotNumber = 0x8B; IYubiKeyDevice testDevice = IntegrationTestDeviceEnumeration.GetTestDevice(testDeviceType); - LoadKeyAndCert (slotNumber, pivPrivateKey, certObj, testDevice); + LoadKeyAndCert(slotNumber, pivPrivateKey, certObj, testDevice); using (var pivSession = new PivSession(testDevice)) { diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/ChangePinWithDerivedTests.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/ChangePinWithDerivedTests.cs index 9d4697ad..9815ba5c 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/ChangePinWithDerivedTests.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/ChangePinWithDerivedTests.cs @@ -13,9 +13,9 @@ // limitations under the License. using System; +using Xunit; using Yubico.YubiKey.Piv.Objects; using Yubico.YubiKey.TestUtilities; -using Xunit; namespace Yubico.YubiKey.Piv { @@ -25,6 +25,7 @@ namespace Yubico.YubiKey.Piv // set of bytes, followed by 2048 random bytes. If you want to get only // random bytes, skip the first SpecifiedStart bytes (get a random object and // generate that many bytes). + [Trait("Category", "Simple")] public class ChangePinWithDerivedTests : IDisposable { private readonly IYubiKeyDevice yubiKey; @@ -62,11 +63,11 @@ public void SetPinOnly_TryChangePin_DerivedKeyUpdated() using (var pivSession = new PivSession(yubiKey)) { - bool isValid = pivSession.TryReadObject(out AdminData adminData); + bool isValid = pivSession.TryReadObject(out AdminData adminData); using (adminData) { Assert.True(isValid); - Assert.NotNull(adminData.Salt); + _ = Assert.NotNull(adminData.Salt); Assert.False(adminData.PinProtected); if (!(adminData.Salt is null)) @@ -79,10 +80,10 @@ public void SetPinOnly_TryChangePin_DerivedKeyUpdated() using (var pivSession = new PivSession(yubiKey)) { - byte[] currentPin = new byte[] { + byte[] currentPin = { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36 }; - byte[] newPin = new byte[] { + byte[] newPin = { 0x39, 0x32, 0x33, 0x34, 0x35, 0x36 }; @@ -107,12 +108,12 @@ public void SetPinOnly_TryChangePin_DerivedKeyUpdated() using (var pivSession = new PivSession(yubiKey)) { - bool isValid = pivSession.TryReadObject(out AdminData adminData); + bool isValid = pivSession.TryReadObject(out AdminData adminData); using (adminData) { Assert.True(isValid); - Assert.NotNull(adminData.PinLastUpdated); - Assert.NotNull(adminData.Salt); + _ = Assert.NotNull(adminData.PinLastUpdated); + _ = Assert.NotNull(adminData.Salt); Assert.False(adminData.PinProtected); if (!(adminData.Salt is null)) @@ -120,7 +121,7 @@ public void SetPinOnly_TryChangePin_DerivedKeyUpdated() var src = (ReadOnlyMemory)adminData.Salt; src.CopyTo(secondSalt); - bool isSame = MemoryExtensions.SequenceEqual(firstSalt.Span, secondSalt.Span); + bool isSame = firstSalt.Span.SequenceEqual(secondSalt.Span); Assert.False(isSame); } } @@ -134,10 +135,10 @@ public void SetPinOnly_ChangeRetryCount_DerivedKeyUpdated(int whichCall) { using (var pivSession = new PivSession(yubiKey)) { - byte[] currentPin = new byte[] { + byte[] currentPin = { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36 }; - byte[] newPin = new byte[] { + byte[] newPin = { 0x39, 0x32, 0x33, 0x34, 0x35, 0x36 }; @@ -166,7 +167,7 @@ public void SetPinOnly_ChangeRetryCount_DerivedKeyUpdated(int whichCall) using (var pivSession = new PivSession(yubiKey)) { - byte[] currentPin = new byte[] { + byte[] currentPin = { 0x39, 0x32, 0x33, 0x34, 0x35, 0x36 }; @@ -201,12 +202,12 @@ public void SetPinOnly_ChangeRetryCount_DerivedKeyUpdated(int whichCall) using (var pivSession = new PivSession(yubiKey)) { - bool isValid = pivSession.TryReadObject(out AdminData adminData); + bool isValid = pivSession.TryReadObject(out AdminData adminData); using (adminData) { Assert.True(isValid); - Assert.NotNull(adminData.PinLastUpdated); - Assert.NotNull(adminData.Salt); + _ = Assert.NotNull(adminData.PinLastUpdated); + _ = Assert.NotNull(adminData.Salt); Assert.False(adminData.PinProtected); } } @@ -239,11 +240,11 @@ public void SetBothPinOnly_ChangePin_KeysUpdated(int whichCall) var collectorObj = new Simple39KeyCollector(); pivSession.KeyCollector = collectorObj.Simple39KeyCollectorDelegate; - bool isValid = pivSession.TryReadObject(out PinProtectedData pinProtect); + bool isValid = pivSession.TryReadObject(out PinProtectedData pinProtect); using (pinProtect) { Assert.True(isValid); - Assert.NotNull(pinProtect.ManagementKey); + _ = Assert.NotNull(pinProtect.ManagementKey); if (!(pinProtect.ManagementKey is null)) { var src = (ReadOnlyMemory)pinProtect.ManagementKey; @@ -299,11 +300,11 @@ public void SetBothPinOnly_ChangePin_KeysUpdated(int whichCall) }; pivSession.KeyCollector = collectorObj.Simple39KeyCollectorDelegate; - bool isValid = pivSession.TryReadObject(out PinProtectedData pinProtect); + bool isValid = pivSession.TryReadObject(out PinProtectedData pinProtect); using (pinProtect) { Assert.True(isValid); - Assert.NotNull(pinProtect.ManagementKey); + _ = Assert.NotNull(pinProtect.ManagementKey); if (!(pinProtect.ManagementKey is null)) { var src = (ReadOnlyMemory)pinProtect.ManagementKey; @@ -312,7 +313,7 @@ public void SetBothPinOnly_ChangePin_KeysUpdated(int whichCall) Assert.True(isValid); Assert.True(pivSession.ManagementKeyAuthenticated); - bool isSame = MemoryExtensions.SequenceEqual(firstKey.Span, secondKey.Span); + bool isSame = firstKey.Span.SequenceEqual(secondKey.Span); Assert.False(isSame); } } @@ -320,12 +321,12 @@ public void SetBothPinOnly_ChangePin_KeysUpdated(int whichCall) using (var pivSession = new PivSession(yubiKey)) { - bool isValid = pivSession.TryReadObject(out AdminData adminData); + bool isValid = pivSession.TryReadObject(out AdminData adminData); using (adminData) { Assert.True(isValid); - Assert.NotNull(adminData.PinLastUpdated); - Assert.NotNull(adminData.Salt); + _ = Assert.NotNull(adminData.PinLastUpdated); + _ = Assert.NotNull(adminData.Salt); Assert.True(adminData.PinProtected); } } diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/Commands/AuthMgmtKeyCmdTests.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/Commands/AuthMgmtKeyCmdTests.cs index dee5635b..a1870888 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/Commands/AuthMgmtKeyCmdTests.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/Commands/AuthMgmtKeyCmdTests.cs @@ -13,8 +13,8 @@ // limitations under the License. using System; -using Yubico.YubiKey.TestUtilities; using Xunit; +using Yubico.YubiKey.TestUtilities; namespace Yubico.YubiKey.Piv.Commands { @@ -24,6 +24,7 @@ namespace Yubico.YubiKey.Piv.Commands // set of bytes, followed by 2048 random bytes. If you want to get only // random bytes, skip the first SpecifiedStart bytes (get a random object and // generate that many bytes). + [Trait("Category", "Simple")] public class AuthMgmtKeyCmdTests : IDisposable { private readonly IYubiKeyDevice yubiKey; @@ -42,14 +43,14 @@ public void Dispose() [Fact] public void AuthKey_Default_Succeeds() { - if (yubiKey.FirmwareVersion < new FirmwareVersion(5,4,2)) + if (yubiKey.FirmwareVersion < new FirmwareVersion(5, 4, 2)) { return; } using (var pivSession = new PivSession(yubiKey)) { - byte[] mgmtKey = new byte[] { + byte[] mgmtKey = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08 @@ -69,19 +70,19 @@ public void AuthKey_Default_Succeeds() [Fact] public void AuthKey_Aes_Succeeds() { - if (yubiKey.FirmwareVersion < new FirmwareVersion(5,4,2)) + if (yubiKey.FirmwareVersion < new FirmwareVersion(5, 4, 2)) { return; } using (var pivSession = new PivSession(yubiKey)) { - byte[] defaultKey = new byte[] { + byte[] defaultKey = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08 }; - byte[] mgmtKey = new byte[] { + byte[] mgmtKey = { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58 diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/Commands/GetMetadataCmdTests.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/Commands/GetMetadataCmdTests.cs index 9e5ebcaa..f1c5dbb6 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/Commands/GetMetadataCmdTests.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/Commands/GetMetadataCmdTests.cs @@ -13,8 +13,8 @@ // limitations under the License. using System; -using Yubico.YubiKey.TestUtilities; using Xunit; +using Yubico.YubiKey.TestUtilities; namespace Yubico.YubiKey.Piv.Commands { @@ -61,7 +61,7 @@ public void AesKey_GetMetadata_CorrectAlgorithm(PivAlgorithm algorithm) bool isValid = pivSession.TryAuthenticateManagementKey(); Assert.True(isValid); - byte[] keyData = new byte[] { + byte[] keyData = { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/Commands/SetMgmtKeyCmdTests.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/Commands/SetMgmtKeyCmdTests.cs index 46f758e9..a030e3b6 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/Commands/SetMgmtKeyCmdTests.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/Commands/SetMgmtKeyCmdTests.cs @@ -13,8 +13,8 @@ // limitations under the License. using System; -using Yubico.YubiKey.TestUtilities; using Xunit; +using Yubico.YubiKey.TestUtilities; namespace Yubico.YubiKey.Piv.Commands { @@ -38,7 +38,7 @@ public void Dispose() [Fact] public void SetKey_ValidAes_Succeeds() { - if (yubiKey.FirmwareVersion < new FirmwareVersion(5,4,2)) + if (yubiKey.FirmwareVersion < new FirmwareVersion(5, 4, 2)) { return; } @@ -48,7 +48,7 @@ public void SetKey_ValidAes_Succeeds() var collectorObj = new Simple39KeyCollector(); pivSession.KeyCollector = collectorObj.Simple39KeyCollectorDelegate; - byte[] keyData = new byte[] { + byte[] keyData = { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38 }; @@ -65,13 +65,13 @@ public void SetKey_ValidAes_Succeeds() setRsp = pivSession.Connection.SendCommand(setCmd); Assert.Equal(ResponseStatus.Success, setRsp.Status); - } + } } [Fact] public void SetKey_Aes256_Succeeds() { - if (yubiKey.FirmwareVersion < new FirmwareVersion(5,4,2)) + if (yubiKey.FirmwareVersion < new FirmwareVersion(5, 4, 2)) { return; } @@ -84,7 +84,7 @@ public void SetKey_Aes256_Succeeds() bool isValid = pivSession.TryAuthenticateManagementKey(); Assert.True(isValid); - byte[] keyData = new byte[] { + byte[] keyData = { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, @@ -100,7 +100,7 @@ public void SetKey_Aes256_Succeeds() [Fact] public void SetKey_TDes_Succeeds() { - if (yubiKey.FirmwareVersion < new FirmwareVersion(5,4,2)) + if (yubiKey.FirmwareVersion < new FirmwareVersion(5, 4, 2)) { return; } @@ -113,7 +113,7 @@ public void SetKey_TDes_Succeeds() bool isValid = pivSession.TryAuthenticateManagementKey(); Assert.True(isValid); - byte[] keyData = new byte[] { + byte[] keyData = { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58 diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/DecryptTests.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/DecryptTests.cs index ff673e8c..b6647641 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/DecryptTests.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/DecryptTests.cs @@ -15,12 +15,13 @@ using System; using System.Linq; using System.Security.Cryptography; +using Xunit; using Yubico.YubiKey.Cryptography; using Yubico.YubiKey.TestUtilities; -using Xunit; namespace Yubico.YubiKey.Piv { + [Trait("Category", "Simple")] public class DecryptTests { [Theory] @@ -28,7 +29,7 @@ public class DecryptTests [InlineData(PivPinPolicy.Never, StandardTestDevice.Fw5)] public void Decrypt_1024_Succeeds(PivPinPolicy pinPolicy, StandardTestDevice testDeviceType) { - byte[] dataToDecrypt = new byte[] { + byte[] dataToDecrypt = { 0x64, 0x92, 0xd1, 0x38, 0x24, 0x8a, 0x78, 0xe5, 0x64, 0x68, 0x92, 0xe7, 0x13, 0xc6, 0x81, 0xa0, 0xe9, 0xeb, 0x43, 0x8f, 0x54, 0x76, 0x55, 0x84, 0x16, 0x3e, 0x47, 0x76, 0x31, 0x6a, 0xc2, 0x7d, 0x27, 0x0f, 0x6c, 0x4f, 0xd5, 0x17, 0x52, 0xea, 0x3e, 0xce, 0xe5, 0xd6, 0x5c, 0x09, 0xac, 0xc2, @@ -61,7 +62,7 @@ public void Decrypt_1024_Succeeds(PivPinPolicy pinPolicy, StandardTestDevice tes [InlineData(PivPinPolicy.Never, StandardTestDevice.Fw5)] public void Decrypt_2048_Succeeds(PivPinPolicy pinPolicy, StandardTestDevice testDeviceType) { - byte[] dataToDecrypt = new byte[] { + byte[] dataToDecrypt = { 0x64, 0x92, 0xd1, 0x38, 0x24, 0x8a, 0x78, 0xe5, 0x64, 0x68, 0x92, 0xe7, 0x13, 0xc6, 0x81, 0xa0, 0xe9, 0xeb, 0x43, 0x8f, 0x54, 0x76, 0x55, 0x84, 0x16, 0x3e, 0x47, 0x76, 0x31, 0x6a, 0xc2, 0x7d, 0x27, 0x0f, 0x6c, 0x4f, 0xd5, 0x17, 0x52, 0xea, 0x3e, 0xce, 0xe5, 0xd6, 0x5c, 0x09, 0xac, 0xc2, @@ -185,7 +186,7 @@ public void NoKeyInSlot_Decrypt_Exception(StandardTestDevice testDeviceType) // Fill a byte array with "random" data. Up to 256 bytes. private static void GetArbitraryData(byte[] bufferToFill) { - byte[] arbitraryData = new byte[] { + byte[] arbitraryData = { 0x3E, 0xE8, 0xC1, 0xBE, 0xFB, 0x55, 0x48, 0x82, 0xE6, 0xAD, 0x9A, 0xBC, 0x84, 0x04, 0xF4, 0xA4, 0xF0, 0xE3, 0x08, 0x53, 0x02, 0x03, 0x01, 0x00, 0x01, 0x02, 0x41, 0x00, 0xAA, 0xA0, 0xBB, 0x04, 0x9E, 0xD7, 0xBA, 0x33, 0x0D, 0x44, 0x84, 0xEC, 0x30, 0x0A, 0xB0, 0x8E, 0xF2, 0x47, 0x1D, 0x89, diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/GenerateTests.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/GenerateTests.cs index 677a39e7..d8f1c8d1 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/GenerateTests.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/GenerateTests.cs @@ -12,24 +12,25 @@ // See the License for the specific language governing permissions and // limitations under the License. +using Xunit; using Yubico.YubiKey.Piv.Commands; using Yubico.YubiKey.Scp03; using Yubico.YubiKey.TestUtilities; -using Xunit; namespace Yubico.YubiKey.Piv { + [Trait("Category", "Simple")] public class GenerateTests { [Fact] public void SimpleGenerate() { IYubiKeyDevice testDevice = IntegrationTestDeviceEnumeration.GetTestDevice( - Transport.SmartCard, FirmwareVersion.V5_3_0); + Transport.SmartCard, minimumFirmwareVersion: FirmwareVersion.V5_3_0); + Assert.True(testDevice.AvailableUsbCapabilities.HasFlag(YubiKeyCapabilities.Piv)); var scp03Keys = new StaticKeys(); - using (var pivSession = new PivSession(testDevice, scp03Keys)) { var collectorObj = new Simple39KeyCollector(); @@ -133,7 +134,7 @@ private static bool DoSignWithPin( bool returnValue = signature1[10] == signature2[10]; - if ((algorithm == PivAlgorithm.EccP256) || (algorithm == PivAlgorithm.EccP384)) + if (algorithm == PivAlgorithm.EccP256 || algorithm == PivAlgorithm.EccP384) { returnValue = signature1[11] != signature2[11]; } diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/GetPutDataTests.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/GetPutDataTests.cs index 65b87380..267221b6 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/GetPutDataTests.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/GetPutDataTests.cs @@ -14,11 +14,11 @@ using System; using System.Security.Cryptography.X509Certificates; +using Xunit; +using Yubico.Core.Tlv; using Yubico.YubiKey.Piv.Commands; using Yubico.YubiKey.Scp03; using Yubico.YubiKey.TestUtilities; -using Yubico.Core.Tlv; -using Xunit; namespace Yubico.YubiKey.Piv { @@ -32,7 +32,7 @@ public void Cert_Auth_Req() Assert.True(isValid); byte[] certDer = cert.GetRawCertData(); - byte[] feData = new byte[] { 0xFE, 0x00 }; + byte[] feData = { 0xFE, 0x00 }; var tlvWriter = new TlvWriter(); using (tlvWriter.WriteNestedTlv(0x53)) { @@ -40,6 +40,7 @@ public void Cert_Auth_Req() tlvWriter.WriteByte(0x71, 0); tlvWriter.WriteEncoded(feData); } + byte[] certData = tlvWriter.Encode(); tlvWriter.Clear(); @@ -51,7 +52,8 @@ public void Cert_Auth_Req() pivSession.KeyCollector = MgmtKeyOnlyKeyCollectorDelegate; pivSession.AuthenticateManagementKey(); - pivSession.ImportPrivateKey(PivSlot.Authentication, privateKey, PivPinPolicy.Never, PivTouchPolicy.Never); + pivSession.ImportPrivateKey(PivSlot.Authentication, privateKey, PivPinPolicy.Never, + PivTouchPolicy.Never); } using (var pivSession = new PivSession(testDevice)) @@ -103,7 +105,7 @@ public void Cert_Auth_Req() [Fact] public void Chuid_Auth_Req() { - byte[] chuidData = new byte[] { + byte[] chuidData = { 0x53, 0x3b, 0x30, 0x19, 0xd4, 0xe7, 0x39, 0xda, 0x73, 0x9c, 0xed, 0x39, 0xce, 0x73, 0x9d, 0x83, 0x68, 0x58, 0x21, 0x08, 0x42, 0x10, 0x84, 0x21, 0xc8, 0x42, 0x10, 0xc3, 0xeb, 0x34, 0x10, 0x39, 0x38, 0x37, 0x36, 0x35, 0x34, 0x33, 0x32, 0x49, 0x48, 0x47, 0x46, 0x45, 0x44, 0x43, 0x42, 0x35, @@ -164,7 +166,7 @@ public void Chuid_Auth_Req() [Fact] public void Capability_Auth_Req() { - byte[] capabilityData = new byte[] { + byte[] capabilityData = { 0x53, 0x33, 0xF0, 0x15, 0xA0, 0x00, 0x00, 0x01, 0x16, 0xFF, 0x02, 0x21, 0x08, 0x42, 0x10, 0x84, 0x21, 0xc8, 0x42, 0x10, 0xc3, 0xeb, 0x34, 0x10, 0x39, 0xF1, 0x01, 0x21, 0xF2, 0x01, 0x21, 0xF3, 0x00, 0xF4, 0x01, 0x00, 0xF5, 0x01, 0x10, 0xF6, 0x00, 0xF7, 0x00, 0xFA, 0x00, 0xFB, 0x00, 0xFC, @@ -231,7 +233,7 @@ public void Capability_Auth_Req() [Fact] public void Discovery_Auth_Req() { - byte[] discoveryData = new byte[] { + byte[] discoveryData = { 0x7E, 0x12, 0x4F, 0x0B, 0xA0, 0x00, 0x00, 0x03, 0x08, 0x00, 0x00, 0x10, 0x00, 0x01, 0x00, 0x5F, 0x2F, 0x02, 0x40, 0x00, }; @@ -253,23 +255,24 @@ public void Discovery_Auth_Req() // Now put some data. // This should throw an exception, it doesn't matter what has or // has not been verified/authenticated. - _ = Assert.Throws(() => new PutDataCommand((int)PivDataTag.Discovery, discoveryData)); + _ = Assert.Throws(() => + new PutDataCommand((int)PivDataTag.Discovery, discoveryData)); } } [Fact] public void Printed_Auth_Req() { - byte[] printedData = new byte[] { + byte[] printedData = { 0x53, 0x04, 0x04, 0x02, 0xd4, 0xe7 }; - byte[] key1 = new byte[] { + byte[] key1 = { 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0x00, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff }; - byte[] key2 = new byte[] { + byte[] key2 = { 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0x00, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff, 0x11 }; - byte[] key3 = new byte[] { + byte[] key3 = { 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0x00, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff, 0x11, 0x22 }; var newKeys = new StaticKeys(key2, key1, key3) @@ -373,7 +376,7 @@ public void Printed_Auth_Req() [InlineData(StandardTestDevice.Fw5)] public void Security_Auth_Req(StandardTestDevice testDeviceType) { - byte[] securityData = new byte[] { + byte[] securityData = { 0x53, 0x08, 0xBA, 0x01, 0x11, 0xBB, 0x01, 0x22, 0xFE, 0x00 }; @@ -431,7 +434,7 @@ public void Security_Auth_Req(StandardTestDevice testDeviceType) [Fact] public void KeyHistory_Auth_Req() { - byte[] keyHistoryData = new byte[] { + byte[] keyHistoryData = { 0x53, 0x0A, 0xC1, 0x01, 0x00, 0xC2, 0x01, 0x00, 0xF3, 0x00, 0xFE, 0x00 }; @@ -490,7 +493,7 @@ public void KeyHistory_Auth_Req() [InlineData(StandardTestDevice.Fw5)] public void Iris_Auth_Req(StandardTestDevice testDeviceType) { - byte[] irisData = new byte[] { + byte[] irisData = { 0x53, 0x05, 0xBC, 0x01, 0x11, 0xFE, 0x00 }; @@ -589,7 +592,7 @@ public void Iris_Auth_Req(StandardTestDevice testDeviceType) [InlineData(StandardTestDevice.Fw5)] public void Facial_Auth_Req(StandardTestDevice testDeviceType) { - byte[] facialData = new byte[] { + byte[] facialData = { 0x53, 0x05, 0xBC, 0x01, 0x11, 0xFE, 0x00 }; @@ -688,7 +691,7 @@ public void Facial_Auth_Req(StandardTestDevice testDeviceType) [InlineData(StandardTestDevice.Fw5)] public void Fingerprint_Auth_Req(StandardTestDevice testDeviceType) { - byte[] fingerprintData = new byte[] { + byte[] fingerprintData = { 0x53, 0x05, 0xBC, 0x01, 0x11, 0xFE, 0x00 }; @@ -787,7 +790,7 @@ public void Fingerprint_Auth_Req(StandardTestDevice testDeviceType) [InlineData(StandardTestDevice.Fw5)] public void Bitgt_Auth_Req(StandardTestDevice testDeviceType) { - byte[] bitgtData = new byte[] { + byte[] bitgtData = { 0x7F, 0x61, 0x07, 0x02, 0x01, 0x01, 0x7F, 0x60, 0x01, 0x01 }; @@ -808,7 +811,8 @@ public void Bitgt_Auth_Req(StandardTestDevice testDeviceType) // This should throw an exception because the SDK does not allow // putting BITGT data. #pragma warning disable CS0618 // Testing an obsolete feature - _ = Assert.Throws(() => new PutDataCommand(PivDataTag.BiometricGroupTemplate, bitgtData)); + _ = Assert.Throws(() => + new PutDataCommand(PivDataTag.BiometricGroupTemplate, bitgtData)); #pragma warning restore CS0618 // Type or member is obsolete } } @@ -817,7 +821,7 @@ public void Bitgt_Auth_Req(StandardTestDevice testDeviceType) [InlineData(StandardTestDevice.Fw5)] public void SMSigner_Auth_Req(StandardTestDevice testDeviceType) { - byte[] smSignerData = new byte[] { + byte[] smSignerData = { 0x53, 0x08, 0x70, 0x01, 0x11, 0x71, 0x01, 0x00, 0xFE, 0x00 }; @@ -878,7 +882,7 @@ public void SMSigner_Auth_Req(StandardTestDevice testDeviceType) [InlineData(StandardTestDevice.Fw5)] public void PCRef_Auth_Req(StandardTestDevice testDeviceType) { - byte[] pcRefData = new byte[] { + byte[] pcRefData = { 0x53, 0x0C, 0x99, 0x08, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0xFE, 0x00 }; @@ -938,7 +942,7 @@ public void PCRef_Auth_Req(StandardTestDevice testDeviceType) [Fact] public void AdminData_Auth_Req() { - byte[] adminData = new byte[] { + byte[] adminData = { 0x53, 0x09, 0x80, 0x07, 0x81, 0x01, 0x00, 0x03, 0x02, 0x5C, 0x29 }; @@ -1000,7 +1004,7 @@ public static bool PinOnlyKeyCollectorDelegate(KeyEntryData keyEntryData) return false; } - if (keyEntryData.IsRetry == true) + if (keyEntryData.IsRetry) { return false; } @@ -1025,7 +1029,7 @@ public static bool MgmtKeyOnlyKeyCollectorDelegate(KeyEntryData keyEntryData) return false; } - if (keyEntryData.IsRetry == true) + if (keyEntryData.IsRetry) { return false; } @@ -1035,7 +1039,8 @@ public static bool MgmtKeyOnlyKeyCollectorDelegate(KeyEntryData keyEntryData) return false; } - keyEntryData.SubmitValue(new byte[] { + keyEntryData.SubmitValue(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 diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/ImportTests.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/ImportTests.cs index 988c2d05..5b09980a 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/ImportTests.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/ImportTests.cs @@ -13,11 +13,12 @@ // limitations under the License. using System.Security.Cryptography.X509Certificates; -using Yubico.YubiKey.TestUtilities; using Xunit; +using Yubico.YubiKey.TestUtilities; namespace Yubico.YubiKey.Piv { + [Trait("Category", "Simple")] public class ImportTests { [Theory] @@ -63,7 +64,7 @@ public void KeyAndCertImport(StandardTestDevice testDeviceType) pivSession.ImportPrivateKey(0x90, privateKey); - pivSession.ImportCertificate(0x90, cert ); + pivSession.ImportCertificate(0x90, cert); } } diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/KeyAgreeTests.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/KeyAgreeTests.cs index 38247709..4a6178a3 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/KeyAgreeTests.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/KeyAgreeTests.cs @@ -15,12 +15,13 @@ using System; using System.Linq; using System.Security.Cryptography; +using Xunit; using Yubico.YubiKey.Cryptography; using Yubico.YubiKey.TestUtilities; -using Xunit; namespace Yubico.YubiKey.Piv { + [Trait("Category", "Simple")] public class KeyAgreeTests { [Theory] diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/ManagementKeyTests.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/ManagementKeyTests.cs index cdf97678..7e82dc93 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/ManagementKeyTests.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/ManagementKeyTests.cs @@ -14,27 +14,30 @@ using System; using System.Security.Cryptography; -using Yubico.YubiKey.TestUtilities; using Xunit; using Xunit.Abstractions; +using Yubico.YubiKey.TestUtilities; namespace Yubico.YubiKey.Piv { + [Trait("Category", "Simple")] public class ManagementKeyTests { - private readonly ITestOutputHelper _output; private readonly byte[] _currentKey; private readonly byte[] _newKey; + private readonly ITestOutputHelper _output; - public ManagementKeyTests (ITestOutputHelper output) + public ManagementKeyTests(ITestOutputHelper output) { _output = output; - _currentKey = new byte[] { + _currentKey = 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 }; - _newKey = new byte[] { + _newKey = 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 @@ -49,7 +52,6 @@ public void HasFeature_ReturnsCorrect() bool expectedResult = false; if (testDevice.FirmwareVersion >= new FirmwareVersion(5, 4, 2)) { - expectedResult = true; } @@ -139,9 +141,9 @@ public bool TestKeyCollectorDelegate(KeyEntryData keyEntryData) return false; } - if (keyEntryData.IsRetry == true) + if (keyEntryData.IsRetry) { - _output.WriteLine ("Retry"); + _output.WriteLine("Retry"); return false; } diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/MgmtKeyNoCollectorTests.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/MgmtKeyNoCollectorTests.cs index bd8188c1..b76a0fca 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/MgmtKeyNoCollectorTests.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/MgmtKeyNoCollectorTests.cs @@ -13,11 +13,12 @@ // limitations under the License. using System; -using Yubico.YubiKey.TestUtilities; using Xunit; +using Yubico.YubiKey.TestUtilities; namespace Yubico.YubiKey.Piv { + [Trait("Category", "Simple")] public class MgmtKeyNoCollectorTests { [Theory] diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/MsrootsTests.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/MsrootsTests.cs index 334ed605..11adb169 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/MsrootsTests.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/MsrootsTests.cs @@ -16,10 +16,10 @@ using System.IO; using System.Linq; using System.Security.Cryptography; -using Yubico.YubiKey.Piv.Commands; -using Yubico.YubiKey.TestUtilities; using Xunit; using Xunit.Abstractions; +using Yubico.YubiKey.Piv.Commands; +using Yubico.YubiKey.TestUtilities; namespace Yubico.YubiKey.Piv { @@ -27,7 +27,7 @@ public class MsrootsTests { private readonly ITestOutputHelper _output; - public MsrootsTests (ITestOutputHelper output) + public MsrootsTests(ITestOutputHelper output) { _output = output; } @@ -52,7 +52,7 @@ public void SimplePutDataCommand(StandardTestDevice testDeviceType) isValid = pivSession.TryAuthenticateManagementKey(); Assert.True(isValid); - byte[] putData = new byte[] { 0x53, 0x04, 0x11, 0x22, 0x33, 0x44 }; + byte[] putData = { 0x53, 0x04, 0x11, 0x22, 0x33, 0x44 }; for (int index = 0; index < 5; index++) { var putCommand = new PutDataCommand(0x005fff11 + index, putData); @@ -101,7 +101,7 @@ public void WriteDataSession(StandardTestDevice testDeviceType) pivSession.ResetApplication(); - byte[] putData = new byte[] { 0x11, 0x22, 0x33, 0x44 }; + byte[] putData = { 0x11, 0x22, 0x33, 0x44 }; pivSession.WriteMsroots(putData); pivSession.WriteMsroots(ReadOnlySpan.Empty); @@ -132,11 +132,11 @@ public void WriteDataSessionBig(StandardTestDevice testDeviceType) FirmwareVersion versionNumber = versionResponse.GetData(); -// int maxLength = 10175; + // int maxLength = 10175; int maxLength = 10150; if (versionNumber.Major >= 4) { -// maxLength = 15295; + // maxLength = 15295; maxLength = 14000; } @@ -259,7 +259,7 @@ public void WriteMsroots_Commands(StandardTestDevice testDeviceType) for (int bufferSize = 2806; bufferSize <= 2808; bufferSize++) { - _output.WriteLine ("buffer size: {0}", bufferSize); + _output.WriteLine("buffer size: {0}", bufferSize); pivSession.ResetApplication(); @@ -294,7 +294,7 @@ private static bool DoWriteAndWrite(PivSession pivSession, byte[] putData) Assert.Equal(ResponseStatus.Success, putResponse.Status); } - byte[] noData = new byte[] { 0x53, 0x00 }; + byte[] noData = { 0x53, 0x00 }; for (int index = 0; index < 5; index++) { var putCommand = new PutDataCommand(0x005fff11 + index, noData); diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/OaepTests.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/OaepTests.cs index 44e19f42..f666ea68 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/OaepTests.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/OaepTests.cs @@ -13,10 +13,10 @@ // limitations under the License. using System.Security.Cryptography; +using Xunit; using Yubico.YubiKey.Cryptography; using Yubico.YubiKey.Piv.Commands; using Yubico.YubiKey.TestUtilities; -using Xunit; namespace Yubico.YubiKey.Piv { @@ -31,7 +31,7 @@ public void Parse_FromRsaClass(StandardTestDevice testDeviceType) var publicKey = new KeyConverter(publicKeyPem.ToCharArray()); var privateKey = new KeyConverter(privateKeyPem.ToCharArray()); - byte[] dataToEncrypt = new byte[] { + byte[] dataToEncrypt = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20, }; diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/Objects/AdminIntegrationTests.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/Objects/AdminIntegrationTests.cs index 01cf1d4f..b4f33c0c 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/Objects/AdminIntegrationTests.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/Objects/AdminIntegrationTests.cs @@ -13,12 +13,13 @@ // limitations under the License. using System; -using Yubico.YubiKey.TestUtilities; -using Yubico.YubiKey.Piv.Objects; using Xunit; +using Yubico.YubiKey.Piv.Objects; +using Yubico.YubiKey.TestUtilities; namespace Yubico.YubiKey.Piv { + [Trait("Category", "Simple")] public class AdminIntegrationTests { [Theory] @@ -44,7 +45,7 @@ public void ReadAdmin_IsEmpty_Correct(StandardTestDevice testDeviceType) [InlineData(StandardTestDevice.Fw5)] public void WriteAdminData_Read_NotEmpty(StandardTestDevice testDeviceType) { - byte[] salt = new byte[] { + byte[] salt = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08 }; @@ -81,7 +82,7 @@ public void WriteAdminData_Read_NotEmpty(StandardTestDevice testDeviceType) [InlineData(StandardTestDevice.Fw5)] public void WriteAdminData_Read_Correct(StandardTestDevice testDeviceType) { - byte[] salt = new byte[] { + byte[] salt = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08 }; @@ -105,14 +106,14 @@ public void WriteAdminData_Read_Correct(StandardTestDevice testDeviceType) pivSession.WriteObject(admin); AdminData adminCopy = pivSession.ReadObject(); - Assert.NotNull(adminCopy.Salt); - Assert.NotNull(adminCopy.PinLastUpdated); + _ = Assert.NotNull(adminCopy.Salt); + _ = Assert.NotNull(adminCopy.PinLastUpdated); if (!(adminCopy.Salt is null)) { var cmpObj = (ReadOnlyMemory)adminCopy.Salt; var expected = new Span(salt); - bool isValid = MemoryExtensions.SequenceEqual(expected, cmpObj.Span); + bool isValid = expected.SequenceEqual(cmpObj.Span); Assert.True(isValid); } diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/Objects/CccIntegrationTests.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/Objects/CccIntegrationTests.cs index ee3fcc05..90b09127 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/Objects/CccIntegrationTests.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/Objects/CccIntegrationTests.cs @@ -13,12 +13,13 @@ // limitations under the License. using System; -using Yubico.YubiKey.TestUtilities; -using Yubico.YubiKey.Piv.Objects; using Xunit; +using Yubico.YubiKey.Piv.Objects; +using Yubico.YubiKey.TestUtilities; namespace Yubico.YubiKey.Piv { + [Trait("Category", "Simple")] public class CccIntegrationTests { [Theory] @@ -69,7 +70,7 @@ public void WriteThenReadCcc_Data_Correct(StandardTestDevice testDeviceType) ccc = pivSession.ReadObject(); Assert.False(ccc.IsEmpty); - bool isValid = MemoryExtensions.SequenceEqual(expected, ccc.CardIdentifier.Span); + bool isValid = expected.SequenceEqual(ccc.CardIdentifier.Span); Assert.True(isValid); } } @@ -112,7 +113,7 @@ public void AltTag_WriteThenReadCcc_Data_Correct(StandardTestDevice testDeviceTy ccc = pivSession.ReadObject(0x5F1110); Assert.False(ccc.IsEmpty); - bool isValid = MemoryExtensions.SequenceEqual(expected, ccc.CardIdentifier.Span); + bool isValid = expected.SequenceEqual(ccc.CardIdentifier.Span); Assert.True(isValid); } } @@ -161,7 +162,7 @@ public void WriteEmpty_Correct(StandardTestDevice testDeviceType) // Make sure that worked. ccc = pivSession.ReadObject(); Assert.False(ccc.IsEmpty); - bool isValid = MemoryExtensions.SequenceEqual(expected, ccc.CardIdentifier.Span); + bool isValid = expected.SequenceEqual(ccc.CardIdentifier.Span); Assert.True(isValid); // Now write an empty object. diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/Objects/ChangePinTests.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/Objects/ChangePinTests.cs index e7736f46..44c35c86 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/Objects/ChangePinTests.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/Objects/ChangePinTests.cs @@ -13,12 +13,13 @@ // limitations under the License. using System; -using Yubico.YubiKey.TestUtilities; -using Yubico.YubiKey.Piv.Objects; using Xunit; +using Yubico.YubiKey.Piv.Objects; +using Yubico.YubiKey.TestUtilities; namespace Yubico.YubiKey.Piv { + [Trait("Category", "Simple")] public class ChangePinTests { [Theory] @@ -76,7 +77,7 @@ public void AdminData_ChangePin_Updated(StandardTestDevice testDeviceType) Assert.False(adminData.IsEmpty); Assert.True(adminData.PinProtected); - Assert.NotNull(adminData.PinLastUpdated); + _ = Assert.NotNull(adminData.PinLastUpdated); } finally { @@ -148,7 +149,7 @@ public void AdminData_ResetRetry_Updated(StandardTestDevice testDeviceType) Assert.False(adminData.IsEmpty); Assert.True(adminData.PinProtected); - Assert.NotNull(adminData.PinLastUpdated); + _ = Assert.NotNull(adminData.PinLastUpdated); } finally { @@ -220,7 +221,7 @@ public void AdminData_ChangeMgmtKey_NoUpdate(StandardTestDevice testDeviceType) adminData = pivSession.ReadObject(); Assert.False(adminData.IsEmpty); - Assert.NotNull(adminData.PinLastUpdated); + _ = Assert.NotNull(adminData.PinLastUpdated); if (!(adminData.PinLastUpdated is null)) { var check = (DateTime)adminData.PinLastUpdated; diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/Objects/ChuidIntegrationTests.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/Objects/ChuidIntegrationTests.cs index 2c1c82e9..c5217027 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/Objects/ChuidIntegrationTests.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/Objects/ChuidIntegrationTests.cs @@ -13,9 +13,9 @@ // limitations under the License. using System; -using Yubico.YubiKey.TestUtilities; -using Yubico.YubiKey.Piv.Objects; using Xunit; +using Yubico.YubiKey.Piv.Objects; +using Yubico.YubiKey.TestUtilities; namespace Yubico.YubiKey.Piv { @@ -69,7 +69,7 @@ public void WriteThenReadChuid_Data_Correct(StandardTestDevice testDeviceType) chuid = pivSession.ReadObject(); Assert.False(chuid.IsEmpty); - bool isValid = MemoryExtensions.SequenceEqual(expected, chuid.GuidValue.Span); + bool isValid = expected.SequenceEqual(chuid.GuidValue.Span); Assert.True(isValid); } } @@ -112,7 +112,7 @@ public void AltTag_WriteThenReadChuid_Data_Correct(StandardTestDevice testDevice chuid = pivSession.ReadObject(0x5F0010); Assert.False(chuid.IsEmpty); - bool isValid = MemoryExtensions.SequenceEqual(expected, chuid.GuidValue.Span); + bool isValid = expected.SequenceEqual(chuid.GuidValue.Span); Assert.True(isValid); } } @@ -161,7 +161,7 @@ public void WriteEmpty_Correct(StandardTestDevice testDeviceType) // Make sure that worked. chuid = pivSession.ReadObject(); Assert.False(chuid.IsEmpty); - bool isValid = MemoryExtensions.SequenceEqual(expected, chuid.GuidValue.Span); + bool isValid = expected.SequenceEqual(chuid.GuidValue.Span); Assert.True(isValid); // Now write an empty object. diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/Objects/HistoryIntegrationTests.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/Objects/HistoryIntegrationTests.cs index 981fc0d7..dd79db25 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/Objects/HistoryIntegrationTests.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/Objects/HistoryIntegrationTests.cs @@ -13,12 +13,13 @@ // limitations under the License. using System; -using Yubico.YubiKey.TestUtilities; -using Yubico.YubiKey.Piv.Objects; using Xunit; +using Yubico.YubiKey.Piv.Objects; +using Yubico.YubiKey.TestUtilities; namespace Yubico.YubiKey.Piv { + [Trait("Category", "Simple")] public class HistoryIntegrationTests { [Theory] @@ -86,7 +87,7 @@ public void WriteThenReadHistory_Data_Correct(StandardTestDevice testDeviceType) byte[] encodedHistory = historyCopy.Encode(); - bool isValid = MemoryExtensions.SequenceEqual(expected.Span, encodedHistory); + bool isValid = expected.Span.SequenceEqual(encodedHistory); Assert.True(isValid); } } diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/Objects/PinProtectedIntegrationTests.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/Objects/PinProtectedIntegrationTests.cs index 43cc45ca..289f0e03 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/Objects/PinProtectedIntegrationTests.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/Objects/PinProtectedIntegrationTests.cs @@ -13,12 +13,13 @@ // limitations under the License. using System; -using Yubico.YubiKey.TestUtilities; -using Yubico.YubiKey.Piv.Objects; using Xunit; +using Yubico.YubiKey.Piv.Objects; +using Yubico.YubiKey.TestUtilities; namespace Yubico.YubiKey.Piv { + [Trait("Category", "Simple")] public class PinProtectedIntegrationTests { [Theory] @@ -94,14 +95,14 @@ public void WriteMgmtKey_Read_Correct(StandardTestDevice testDeviceType) PinProtectedData pinProtectCopy = pivSession.ReadObject(); - Assert.NotNull(pinProtectCopy.ManagementKey); + _ = Assert.NotNull(pinProtectCopy.ManagementKey); if (!(pinProtectCopy.ManagementKey is null)) { var getData = (ReadOnlyMemory)pinProtectCopy.ManagementKey; - bool isValid = MemoryExtensions.SequenceEqual(mgmtKey.Span, getData.Span); + bool isValid = mgmtKey.Span.SequenceEqual(getData.Span); Assert.True(isValid); } - + } finally { @@ -112,7 +113,7 @@ public void WriteMgmtKey_Read_Correct(StandardTestDevice testDeviceType) private Memory GetArbitraryMgmtKey() { - byte[] keyData = new byte[] { + byte[] keyData = { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68 diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/Objects/TagTests.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/Objects/TagTests.cs index e81dac80..3c46688c 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/Objects/TagTests.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/Objects/TagTests.cs @@ -13,12 +13,13 @@ // limitations under the License. using System; -using Yubico.YubiKey.TestUtilities; -using Yubico.YubiKey.Piv.Commands; using Xunit; +using Yubico.YubiKey.Piv.Commands; +using Yubico.YubiKey.TestUtilities; namespace Yubico.YubiKey.Piv { + [Trait("Category", "Simple")] public class TagTests { [Theory] @@ -38,7 +39,7 @@ public void AlternateTag_Minimum_Succeeds(StandardTestDevice testDeviceType) pivSession.AuthenticateManagementKey(); - byte[] arbitraryData = new byte[] { + byte[] arbitraryData = { 0x53, 0x02, 0x04, 0x00 }; @@ -54,7 +55,7 @@ public void AlternateTag_Minimum_Succeeds(StandardTestDevice testDeviceType) ReadOnlyMemory theData = getRsp.GetData(); - bool isValid = MemoryExtensions.SequenceEqual(arbitraryData, theData.Span); + bool isValid = MemoryExtensions.SequenceEqual(arbitraryData, theData.Span); Assert.True(isValid); } finally @@ -81,7 +82,7 @@ public void AlternateTag_Invalid_Error(StandardTestDevice testDeviceType) pivSession.AuthenticateManagementKey(); - byte[] arbitraryData = new byte[] { + byte[] arbitraryData = { 0x53, 0x02, 0x04, 0x00 }; diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/PinAlwaysTests.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/PinAlwaysTests.cs index db755911..77e55bf3 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/PinAlwaysTests.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/PinAlwaysTests.cs @@ -13,8 +13,8 @@ // limitations under the License. using System.Linq; -using Yubico.YubiKey.TestUtilities; using Xunit; +using Yubico.YubiKey.TestUtilities; namespace Yubico.YubiKey.Piv { @@ -38,7 +38,7 @@ public void PinAlways_Sign_Succeeds(StandardTestDevice testDeviceType) _ = pivSession.GenerateKeyPair( slotNumber, PivAlgorithm.EccP256, PivPinPolicy.Always, PivTouchPolicy.Never); - byte[] dataToSign = new byte[] { + byte[] dataToSign = { 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, @@ -72,7 +72,7 @@ public void Slot9C_Default_Sign_Succeeds(StandardTestDevice testDeviceType) _ = pivSession.GenerateKeyPair( slotNumber, PivAlgorithm.EccP256, PivPinPolicy.Default, PivTouchPolicy.Never); - byte[] dataToSign = new byte[] { + byte[] dataToSign = { 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/PinNoCollectorTests.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/PinNoCollectorTests.cs index eea8e960..38c74c68 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/PinNoCollectorTests.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/PinNoCollectorTests.cs @@ -13,12 +13,13 @@ // limitations under the License. using System; -using Yubico.YubiKey.TestUtilities; -using Yubico.YubiKey.Piv.Objects; using Xunit; +using Yubico.YubiKey.Piv.Objects; +using Yubico.YubiKey.TestUtilities; namespace Yubico.YubiKey.Piv { + [Trait("Category", "Simple")] public class PinNoCollectorTests { [Theory] @@ -56,7 +57,7 @@ public void VerifyPin_WrongPin_ReturnsFalse(StandardTestDevice testDeviceType) pivSession.ResetApplication(); bool isValid = pivSession.TryVerifyPin(pin, out int? retriesRemaining); Assert.False(isValid); - Assert.NotNull(retriesRemaining); + _ = Assert.NotNull(retriesRemaining); if (!(retriesRemaining is null)) { Assert.Equal(2, retriesRemaining); diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/PinOnlyStateTests.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/PinOnlyStateTests.cs index db95c813..15019b82 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/PinOnlyStateTests.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/PinOnlyStateTests.cs @@ -13,10 +13,10 @@ // limitations under the License. using System; -using Yubico.YubiKey.Piv.Objects; +using Xunit; using Yubico.YubiKey.Piv.Commands; +using Yubico.YubiKey.Piv.Objects; using Yubico.YubiKey.TestUtilities; -using Xunit; namespace Yubico.YubiKey.Piv { @@ -26,19 +26,19 @@ public class PinOnlyStateTests : IDisposable { private const int AdminDataTag = 0x005FFF00; private const int PrintedTag = (int)PivDataTag.Printed; - private readonly bool _alternateAlgorithm = false; + private readonly bool _alternateAlgorithm; private readonly IYubiKeyDevice _yubiKey; private readonly SpecifiedKeyCollector _specifiedCollector; private readonly Simple39KeyCollector _collectorObj; private readonly ReadOnlyMemory _defaultManagementKey; private readonly ReadOnlyMemory _defaultPin; - private readonly byte[] _keyBytes = new byte[] { + private readonly byte[] _keyBytes = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08 }; - private readonly byte[] _pinBytes = new byte[] { + private readonly byte[] _pinBytes = { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36 }; @@ -115,7 +115,7 @@ public void ResetToNone_Success( { Assert.Equal(PivAlgorithm.TripleDes, pivSession.ManagementKeyAlgorithm); - bool isValid = pivSession.TryAuthenticateManagementKey(_defaultManagementKey, true); + bool isValid = pivSession.TryAuthenticateManagementKey(_defaultManagementKey); Assert.True(isValid); PivPinOnlyMode expectedMode = GetExpectedMode(PivPinOnlyMode.None, unavailable); @@ -141,7 +141,7 @@ public void StartWithNone_Unavailable_None(PivPinOnlyMode unavailable) { using (var pivSession = new PivSession(_yubiKey)) { - bool isValid = pivSession.TryAuthenticateManagementKey(_defaultManagementKey, true); + bool isValid = pivSession.TryAuthenticateManagementKey(_defaultManagementKey); Assert.True(isValid); isValid = pivSession.TryVerifyPin(_defaultPin, out int? _); @@ -181,7 +181,7 @@ public void Unavailable_Recover(PivPinOnlyMode mode, PivPinOnlyMode unavailable) using (var pivSession = new PivSession(_yubiKey)) { pivSession.KeyCollector = _specifiedCollector.SpecifiedKeyCollectorDelegate; - bool isValid = pivSession.TryAuthenticateManagementKey(true); + bool isValid = pivSession.TryAuthenticateManagementKey(); Assert.True(isValid); SetUnavailable(pivSession, unavailable); @@ -281,7 +281,7 @@ private bool AreContentsExpected( private void SetUnavailable(PivSession pivSession, PivPinOnlyMode unavailable) { - byte[] unexpectedData = new byte[] { 0x53, 0x04, 0x02, 0x02, 0x00, 0xff }; + byte[] unexpectedData = { 0x53, 0x04, 0x02, 0x02, 0x00, 0xff }; if (unavailable.HasFlag(PivPinOnlyMode.PinProtectedUnavailable)) { diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/PinOnlyWithResetTests.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/PinOnlyWithResetTests.cs index fc0f0819..c644d54e 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/PinOnlyWithResetTests.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/PinOnlyWithResetTests.cs @@ -15,9 +15,9 @@ using System; using System.Security; using System.Security.Cryptography; +using Xunit; using Yubico.YubiKey.Piv.Objects; using Yubico.YubiKey.TestUtilities; -using Xunit; namespace Yubico.YubiKey.Piv { @@ -27,6 +27,7 @@ namespace Yubico.YubiKey.Piv // set of bytes, followed by 2048 random bytes. If you want to get only // random bytes, skip the first SpecifiedStart bytes (get a random object and // generate that many bytes). + [Trait("Category", "Simple")] public class PinOnlyWithResetTests : IDisposable { private const int SpecifiedStart = 72; @@ -111,7 +112,7 @@ public void SetPinDerived_GetMode_ReturnsCorrect() Assert.Null(adminData.PinLastUpdated); Assert.False(adminData.PinProtected); Assert.True(adminData.PukBlocked); - Assert.NotNull(adminData.Salt); + _ = Assert.NotNull(adminData.Salt); PinProtectedData pinProtect = pivSession.ReadObject(); Assert.True(pinProtect.IsEmpty); @@ -134,7 +135,7 @@ public void SetPinDerived_GetMode_ReturnsCorrect() bool isBlocked = IsPukBlocked(); Assert.True(isBlocked); - } + } [Fact] public void Run_SetPinDerived_UsesSalt() @@ -148,7 +149,7 @@ public void Run_SetPinDerived_UsesSalt() pivSession.SetPinOnlyMode(PivPinOnlyMode.PinDerived); AdminData adminData = pivSession.ReadObject(); - Assert.NotNull(adminData.Salt); + _ = Assert.NotNull(adminData.Salt); if (!(adminData.Salt is null)) { var result = (ReadOnlyMemory)adminData.Salt; @@ -186,7 +187,7 @@ public void SetPinProtected_GetMode_ReturnsCorrect() PinProtectedData pinProtect = pivSession.ReadObject(); Assert.False(pinProtect.IsEmpty); - Assert.NotNull(pinProtect.ManagementKey); + _ = Assert.NotNull(pinProtect.ManagementKey); } using (var pivSession = new PivSession(yubiKey)) @@ -272,7 +273,7 @@ public void SetProtectThenDerive_CorrectMgmtKey() PinProtectedData pinProtect = pivSession.ReadObject(); Assert.False(pinProtect.IsEmpty); - Assert.NotNull(pinProtect.ManagementKey); + _ = Assert.NotNull(pinProtect.ManagementKey); if (!(pinProtect.ManagementKey is null)) { var result = (ReadOnlyMemory)pinProtect.ManagementKey; @@ -293,7 +294,7 @@ public void SetProtectThenDerive_CorrectMgmtKey() PinProtectedData pinProtect = pivSession.ReadObject(); Assert.False(pinProtect.IsEmpty); - Assert.NotNull(pinProtect.ManagementKey); + _ = Assert.NotNull(pinProtect.ManagementKey); if (!(pinProtect.ManagementKey is null)) { var result = (ReadOnlyMemory)pinProtect.ManagementKey; @@ -317,7 +318,7 @@ public void SetProtect_RejectsWeakKey() PinProtectedData pinProtect = pivSession.ReadObject(); Assert.False(pinProtect.IsEmpty); - Assert.NotNull(pinProtect.ManagementKey); + _ = Assert.NotNull(pinProtect.ManagementKey); if (!(pinProtect.ManagementKey is null)) { var result = (ReadOnlyMemory)pinProtect.ManagementKey; @@ -346,7 +347,7 @@ public void SetProtect_ThenNone_CorrectMode() PinProtectedData pinProtect = pivSession.ReadObject(); Assert.False(pinProtect.IsEmpty); - Assert.NotNull(pinProtect.ManagementKey); + _ = Assert.NotNull(pinProtect.ManagementKey); if (!(pinProtect.ManagementKey is null)) { var result = (ReadOnlyMemory)pinProtect.ManagementKey; @@ -696,7 +697,7 @@ public void SetPinOnly_ThenNone_Success(PivAlgorithm algorithm, PivPinOnlyMode m 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08 }); - bool isValid = pivSession.TryAuthenticateManagementKey(mgmtKey, true); + bool isValid = pivSession.TryAuthenticateManagementKey(mgmtKey); } } diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/PivObjectTests.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/PivObjectTests.cs index 1863f091..35ca1814 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/PivObjectTests.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/PivObjectTests.cs @@ -13,13 +13,14 @@ // limitations under the License. using System; -using Yubico.YubiKey.TestUtilities; +using Xunit; using Yubico.YubiKey.Piv.Commands; using Yubico.YubiKey.Piv.Objects; -using Xunit; +using Yubico.YubiKey.TestUtilities; namespace Yubico.YubiKey.Piv { + [Trait("Category", "Simple")] public class PivObjectTests { [Theory] @@ -70,7 +71,7 @@ public void WriteThenReadChuid_Data_Correct(StandardTestDevice testDeviceType) chuid = pivSession.ReadObject(); Assert.False(chuid.IsEmpty); - bool isValid = MemoryExtensions.SequenceEqual(expected, chuid.GuidValue.Span); + bool isValid = expected.SequenceEqual(chuid.GuidValue.Span); Assert.True(isValid); } } @@ -113,7 +114,7 @@ public void AltTag_WriteThenReadChuid_Data_Correct(StandardTestDevice testDevice chuid = pivSession.ReadObject(0x5F0010); Assert.False(chuid.IsEmpty); - bool isValid = MemoryExtensions.SequenceEqual(expected, chuid.GuidValue.Span); + bool isValid = expected.SequenceEqual(chuid.GuidValue.Span); Assert.True(isValid); } } @@ -162,7 +163,7 @@ public void WriteEmpty_Correct(StandardTestDevice testDeviceType) // Make sure that worked. chuid = pivSession.ReadObject(); Assert.False(chuid.IsEmpty); - bool isValid = MemoryExtensions.SequenceEqual(expected, chuid.GuidValue.Span); + bool isValid = expected.SequenceEqual(chuid.GuidValue.Span); Assert.True(isValid); // Now write an empty object. @@ -243,7 +244,7 @@ public void WriteEmptyObject_DataEmpty(StandardTestDevice testDeviceType) var getDataCommand = new GetDataCommand((int)PivDataTag.Printed); GetDataResponse getDataResponse = pivSession.Connection.SendCommand(getDataCommand); - Assert.Equal (ResponseStatus.Success, getDataResponse.Status); + Assert.Equal(ResponseStatus.Success, getDataResponse.Status); ReadOnlyMemory getData = getDataResponse.GetData(); Assert.Equal(0x53, getData.Span[0]); @@ -272,7 +273,7 @@ public void WriteEmptyObject_DataEmpty(StandardTestDevice testDeviceType) GetDataResponse getDataResponse = pivSession.Connection.SendCommand(getDataCommand); ReadOnlyMemory getData = getDataResponse.GetData(); - Assert.Equal (4, getData.Length); + Assert.Equal(4, getData.Length); } } diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/PivSessionTests.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/PivSessionTests.cs index 33cf3c2d..d6571342 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/PivSessionTests.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/PivSessionTests.cs @@ -14,13 +14,14 @@ using System.Linq; using System.Security.Cryptography; +using Xunit; using Yubico.YubiKey.Cryptography; using Yubico.YubiKey.Piv.Commands; using Yubico.YubiKey.TestUtilities; -using Xunit; namespace Yubico.YubiKey.Piv { + [Trait("Category", "Simple")] public class PivSessionTests { [Theory] @@ -55,7 +56,7 @@ public void VerifyPin_WrongPin(StandardTestDevice testDeviceType) pivSession.KeyCollector = collectorObj.Simple39KeyCollectorDelegate; Assert.True(testDevice.EnabledUsbCapabilities.HasFlag(YubiKeyCapabilities.Piv)); - + collectorObj.KeyFlag = 1; bool isVerified = pivSession.TryVerifyPin(); @@ -80,7 +81,7 @@ public void AuthenticateMgmtKey_Single(StandardTestDevice testDeviceType) { var collectorObj = new Simple39KeyCollector(); pivSession.KeyCollector = collectorObj.Simple39KeyCollectorDelegate; - + Assert.True(testDevice.EnabledUsbCapabilities.HasFlag(YubiKeyCapabilities.Piv)); bool isAuthenticated = pivSession.TryAuthenticateManagementKey(false); @@ -408,7 +409,7 @@ public void ResetPiv(StandardTestDevice testDeviceType) [Fact] public void FixedBytes_Replace() { - byte[] fixedBytes = new byte[] { + byte[] fixedBytes = { 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, @@ -443,7 +444,7 @@ private static bool TryGenerate(PivSession pivSession, byte slotNumber, Response private static bool TrySign(PivSession pivSession, byte slotNumber, ResponseStatus expectedStatus) { - byte[] dataToSign = new byte[] { + byte[] dataToSign = { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/PivSupport.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/PivSupport.cs index d93c9047..6b34b9f3 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/PivSupport.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/PivSupport.cs @@ -33,7 +33,8 @@ public static bool ImportKey(PivSession pivSession, byte slotNumber) } } - var priKey = PivPrivateKey.Create(new byte[] { + var priKey = PivPrivateKey.Create(new byte[] + { 0x06, 0x20, 0xba, 0x29, 0x7a, 0xc6, 0x64, 0x62, 0xef, 0x6c, 0xd0, 0x89, 0x76, 0x5c, 0xbd, 0x46, 0x52, 0x2b, 0xb0, 0x48, 0x0e, 0x85, 0x49, 0x15, 0x85, 0xe7, 0x7a, 0x74, 0x3c, 0x8e, 0x03, 0x59, 0x8d, 0x3a @@ -76,9 +77,9 @@ public static bool ResetPiv(PivSession pivSession) return false; } - if (BlockPinOrPuk(pivSession, PivSlot.Pin) == true) + if (BlockPinOrPuk(pivSession, PivSlot.Pin)) { - if (BlockPinOrPuk(pivSession, PivSlot.Puk) == true) + if (BlockPinOrPuk(pivSession, PivSlot.Puk)) { var resetCommand = new ResetPivCommand(); ResetPivResponse resetResponse = pivSession.Connection.SendCommand(resetCommand); @@ -94,10 +95,10 @@ private static bool BlockPinOrPuk(PivSession pivSession, byte slotNumber) int retriesRemaining; do { - byte[] currentValue = new byte[] { + byte[] currentValue = { 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01 }; - byte[] newValue = new byte[] { + byte[] newValue = { 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22 }; var changeCommand = new ChangeReferenceDataCommand(slotNumber, currentValue, newValue); @@ -109,7 +110,6 @@ private static bool BlockPinOrPuk(PivSession pivSession, byte slotNumber) } retriesRemaining = changeResponse.GetData() ?? 1; - } while (retriesRemaining > 0); return true; diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/PssTests.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/PssTests.cs index f3251066..8059d604 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/PssTests.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/PssTests.cs @@ -13,13 +13,14 @@ // limitations under the License. using System.Security.Cryptography; +using Xunit; using Yubico.YubiKey.Cryptography; using Yubico.YubiKey.Piv.Commands; using Yubico.YubiKey.TestUtilities; -using Xunit; namespace Yubico.YubiKey.Piv { + [Trait("Category", "Simple")] public class PssTests { [Theory] @@ -31,7 +32,7 @@ public void Parse_FromRsaClass(StandardTestDevice testDeviceType) var publicKey = new KeyConverter(publicKeyPem.ToCharArray()); var privateKey = new KeyConverter(privateKeyPem.ToCharArray()); - byte[] dataToSign = new byte[] { + byte[] dataToSign = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20, }; @@ -106,7 +107,7 @@ public void UseKeyConverter(PivAlgorithm algorithm, int keySize) var privateKey = new KeyConverter(privatePem.ToCharArray()); Assert.Equal(algorithm, privateKey.Algorithm); - if ((algorithm == PivAlgorithm.Rsa1024) || (algorithm == PivAlgorithm.Rsa2048)) + if (algorithm == PivAlgorithm.Rsa1024 || algorithm == PivAlgorithm.Rsa2048) { using RSA rsaPublic = publicKey.GetRsaObject(); Assert.Equal(keySize, rsaPublic.KeySize); diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/RecoverPinOnlyTests.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/RecoverPinOnlyTests.cs index 6eae617a..997e6282 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/RecoverPinOnlyTests.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/RecoverPinOnlyTests.cs @@ -13,10 +13,10 @@ // limitations under the License. using System; -using Yubico.YubiKey.Piv.Objects; +using Xunit; using Yubico.YubiKey.Piv.Commands; +using Yubico.YubiKey.Piv.Objects; using Yubico.YubiKey.TestUtilities; -using Xunit; namespace Yubico.YubiKey.Piv { @@ -142,7 +142,7 @@ public void PinProtectedAndDerived_OverwritePrinted_CanRecover() using AdminData adminData = pivSession.ReadObject(); Assert.True(adminData.PinProtected); - Assert.NotNull(adminData.Salt); + _ = Assert.NotNull(adminData.Salt); } using (var pivSession = new PivSession(yubiKey)) diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/RetryTests.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/RetryTests.cs index 57c33120..da97d7d5 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/RetryTests.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/RetryTests.cs @@ -18,6 +18,7 @@ namespace Yubico.YubiKey.Piv { + [Trait("Category", "Simple")] public class RetryTests { [Theory] @@ -35,7 +36,7 @@ public void ChangeRetry_Succeeds(StandardTestDevice testDeviceType) pivSession.ChangePinAndPukRetryCounts(7, 8); - if (isOld == true) + if (isOld) { return; } @@ -73,7 +74,7 @@ public void ChangeRetry_SetsToDefault(StandardTestDevice testDeviceType) collectorObj.KeyFlag = 0; pivSession.VerifyPin(); - if (isOld == true) + if (isOld) { return; } diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/SelectApplicationTests.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/SelectApplicationTests.cs index e192a3c1..3ca8b495 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/SelectApplicationTests.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/SelectApplicationTests.cs @@ -12,11 +12,14 @@ // See the License for the specific language governing permissions and // limitations under the License. -using Yubico.YubiKey.TestUtilities; using Xunit; +using Yubico.YubiKey.InterIndustry.Commands; +using Yubico.YubiKey.Piv.Commands; +using Yubico.YubiKey.TestUtilities; namespace Yubico.YubiKey.Piv { + [Trait("Category", "Simple")] public sealed class SelectApplicationTests { [Theory] @@ -30,10 +33,10 @@ public void ConnectOathHasData(StandardTestDevice testDeviceType) Assert.NotNull(connection); // Connect does not actually select the app. We need a command for this. It can be anything. - _ = connection!.SendCommand(new Piv.Commands.GetSerialNumberCommand()); + _ = connection!.SendCommand(new GetSerialNumberCommand()); Assert.NotNull(connection!.SelectApplicationData); - var data = Assert.IsType(connection.SelectApplicationData); + GenericSelectApplicationData? data = Assert.IsType(connection.SelectApplicationData); Assert.False(data!.RawData.IsEmpty); } diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/SignTests.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/SignTests.cs index d590bbfd..b407e16f 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/SignTests.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/SignTests.cs @@ -14,14 +14,15 @@ using System; using System.Security.Cryptography; +using Xunit; +using Yubico.Core.Tlv; using Yubico.YubiKey.Cryptography; using Yubico.YubiKey.Piv.Commands; using Yubico.YubiKey.TestUtilities; -using Yubico.Core.Tlv; -using Xunit; namespace Yubico.YubiKey.Piv { + [Trait("Category", "Simple")] public class SignTests { [Theory] @@ -29,7 +30,7 @@ public class SignTests [InlineData(PivPinPolicy.Never)] public void Sign_EccP256_Succeeds(PivPinPolicy pinPolicy) { - byte[] dataToSign = new byte[] { + byte[] dataToSign = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20 }; @@ -112,7 +113,8 @@ public void Sign_RandomData_Succeeds(PivAlgorithm algorithm, byte slotNumber) [InlineData(PivAlgorithm.Rsa2048, 0x93, RsaFormat.Sha256, 2)] [InlineData(PivAlgorithm.Rsa2048, 0x93, RsaFormat.Sha384, 2)] [InlineData(PivAlgorithm.Rsa2048, 0x93, RsaFormat.Sha512, 2)] - public void SignRsa_VerifyCSharp_Correct(PivAlgorithm algorithm, byte slotNumber, int digestAlgorithm, int paddingScheme) + public void SignRsa_VerifyCSharp_Correct(PivAlgorithm algorithm, byte slotNumber, int digestAlgorithm, + int paddingScheme) { int keySizeBits = RsaFormat.KeySizeBits1024; if (algorithm != PivAlgorithm.Rsa1024) @@ -240,7 +242,7 @@ public void SignEcc_VerifyCSharp_Correct(PivAlgorithm algorithm, byte slotNumber [InlineData(StandardTestDevice.Fw5)] public void NoKeyInSlot_Sign_Exception(StandardTestDevice testDeviceType) { - byte[] dataToSign = new byte[] { + byte[] dataToSign = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20 }; @@ -258,11 +260,12 @@ public void NoKeyInSlot_Sign_Exception(StandardTestDevice testDeviceType) } } - public static bool LoadKey(PivAlgorithm algorithm, byte slotNumber, PivPinPolicy pinPolicy, PivTouchPolicy touchPolicy, IYubiKeyDevice testDevice) + public static bool LoadKey(PivAlgorithm algorithm, byte slotNumber, PivPinPolicy pinPolicy, + PivTouchPolicy touchPolicy, IYubiKeyDevice testDevice) { if (testDevice != null) { - if (testDevice.AvailableUsbCapabilities.HasFlag(YubiKeyCapabilities.Piv) == true) + if (testDevice.AvailableUsbCapabilities.HasFlag(YubiKeyCapabilities.Piv)) { using (var pivSession = new PivSession(testDevice)) { @@ -292,18 +295,21 @@ public static bool ConvertEcdsaSignature(byte[] signature, int integerLength, ou // Leading 00 bytes? if (rValue.Length > integerLength) { - if ((rValue.Length > (integerLength + 1)) || (rValue.Span[0] != 0)) + if (rValue.Length > integerLength + 1 || rValue.Span[0] != 0) { return false; } + rValue = rValue[1..]; } + if (sValue.Length > integerLength) { - if ((sValue.Length > (integerLength + 1)) || (sValue.Span[0] != 0)) + if (sValue.Length > integerLength + 1 || sValue.Span[0] != 0) { return false; } + sValue = sValue[1..]; } @@ -320,7 +326,7 @@ public static bool ConvertEcdsaSignature(byte[] signature, int integerLength, ou // Fill a byte array with "random" data. Up to 256 bytes. private static void GetArbitraryData(byte[] bufferToFill) { - byte[] arbitraryData = new byte[] { + byte[] arbitraryData = { 0x3E, 0xE8, 0xC1, 0xBE, 0xFB, 0x55, 0x48, 0x82, 0xE6, 0xAD, 0x9A, 0xBC, 0x84, 0x04, 0xF4, 0xA4, 0xF0, 0xE3, 0x08, 0x53, 0x02, 0x03, 0x01, 0x00, 0x01, 0x02, 0x41, 0x00, 0xAA, 0xA0, 0xBB, 0x04, 0x9E, 0xD7, 0xBA, 0x33, 0x0D, 0x44, 0x84, 0xEC, 0x30, 0x0A, 0xB0, 0x8E, 0xF2, 0x47, 0x1D, 0x89, diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/Simple39KeyCollector.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/Simple39KeyCollector.cs index baa6a70f..4828d2ee 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/Simple39KeyCollector.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/Simple39KeyCollector.cs @@ -23,6 +23,18 @@ public class Simple39KeyCollector { private static bool _setKeyFlagOnChange; + // If the caller sets the input arg to true, then when the call asks for + // Change, return the old and new, then set KeyFlag to the opposite of + // what it currently is. + // For false, then this returns old and new, but does nothing to KeyFlag. + // If there is no arg, that's false. + public Simple39KeyCollector(bool setKeyFlagOnChange = false) + { + KeyFlag = 0; + RetryFlag = 0; + _setKeyFlagOnChange = setKeyFlagOnChange; + } + // If KeyFlag is set to 0, the current PIN, PUK, or key returned will be // the default and the new PIN, PUK, or key will be the alternate. // The alternate is the same except the first byte is different: 0x39. @@ -36,18 +48,6 @@ public class Simple39KeyCollector // PUK. This way we can block the PIN or PUK for testing purposes. public int RetryFlag { get; set; } - // If the caller sets the input arg to true, then when the call asks for - // Change, return the old and new, then set KeyFlag to the opposite of - // what it currently is. - // For false, then this returns old and new, but does nothing to KeyFlag. - // If there is no arg, that's false. - public Simple39KeyCollector(bool setKeyFlagOnChange = false) - { - KeyFlag = 0; - RetryFlag = 0; - _setKeyFlagOnChange = setKeyFlagOnChange; - } - public bool Simple39KeyCollectorDelegate(KeyEntryData keyEntryData) { if (keyEntryData is null) @@ -55,7 +55,7 @@ public bool Simple39KeyCollectorDelegate(KeyEntryData keyEntryData) return false; } - if ((keyEntryData.IsRetry == true) && (RetryFlag == 0)) + if (keyEntryData.IsRetry && RetryFlag == 0) { if (!(keyEntryData.RetriesRemaining is null)) { @@ -80,6 +80,7 @@ public bool Simple39KeyCollectorDelegate(KeyEntryData keyEntryData) { KeyFlag = 0; } + return true; case KeyEntryRequest.VerifyPivPin: @@ -105,18 +106,20 @@ public bool Simple39KeyCollectorDelegate(KeyEntryData keyEntryData) break; case KeyEntryRequest.AuthenticatePivManagementKey: - if (keyEntryData.IsRetry == true) + if (keyEntryData.IsRetry) { return false; } + currentValue = CollectMgmtKey(); break; case KeyEntryRequest.ChangePivManagementKey: - if (keyEntryData.IsRetry == true) + if (keyEntryData.IsRetry) { return false; } + currentValue = CollectMgmtKey(); newValue = CollectMgmtKey(); isChange = true; @@ -129,6 +132,7 @@ public bool Simple39KeyCollectorDelegate(KeyEntryData keyEntryData) { currentValue[0] = 0x39; } + keyEntryData.SubmitValue(currentValue); } else @@ -141,6 +145,7 @@ public bool Simple39KeyCollectorDelegate(KeyEntryData keyEntryData) { newValue[0] = 0x39; } + keyEntryData.SubmitValues(currentValue, newValue); } @@ -166,10 +171,11 @@ public static byte[] CollectPuk() => new byte[] { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38 }; public static byte[] CollectMgmtKey() => - 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 - }; + 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 + }; } } diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/SpecifiedKeyCollector.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/SpecifiedKeyCollector.cs index 01279021..5d077c25 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/SpecifiedKeyCollector.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/SpecifiedKeyCollector.cs @@ -22,9 +22,9 @@ namespace Yubico.YubiKey.Piv // key at construction, and those are the only values it returns. public class SpecifiedKeyCollector { + private readonly byte[] _mgmtKey; private readonly byte[] _pin; private readonly byte[] _puk; - private readonly byte[] _mgmtKey; public SpecifiedKeyCollector(byte[] pin, byte[] puk, byte[] mgmtKey) { @@ -45,7 +45,7 @@ public bool SpecifiedKeyCollectorDelegate(KeyEntryData keyEntryData) return false; } - if (keyEntryData.IsRetry == true) + if (keyEntryData.IsRetry) { return false; } @@ -65,16 +65,16 @@ public bool SpecifiedKeyCollectorDelegate(KeyEntryData keyEntryData) currentValue = _pin; break; -// case KeyEntryRequest.ChangePivPin: -// currentValue = CollectPin(); -// newValue = CollectPin(); -// break; -// -// case KeyEntryRequest.ChangePivPuk: -// currentValue = CollectPuk(); -// newValue = CollectPuk(); -// break; -// + // case KeyEntryRequest.ChangePivPin: + // currentValue = CollectPin(); + // newValue = CollectPin(); + // break; + // + // case KeyEntryRequest.ChangePivPuk: + // currentValue = CollectPuk(); + // newValue = CollectPuk(); + // break; + // case KeyEntryRequest.ResetPivPinWithPuk: currentValue = _puk; newValue = _pin; @@ -84,14 +84,14 @@ public bool SpecifiedKeyCollectorDelegate(KeyEntryData keyEntryData) currentValue = _mgmtKey; break; -// case KeyEntryRequest.ChangePivManagementKey: -// if (keyEntryData.IsRetry == true) -// { -// return false; -// } -// currentValue = CollectMgmtKey(); -// newValue = CollectMgmtKey(); -// break; + // case KeyEntryRequest.ChangePivManagementKey: + // if (keyEntryData.IsRetry == true) + // { + // return false; + // } + // currentValue = CollectMgmtKey(); + // newValue = CollectMgmtKey(); + // break; } if (newValue is null) diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/X500NameBuilder.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/X500NameBuilder.cs index 3cb8d691..e1dd686e 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/X500NameBuilder.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Piv/X500NameBuilder.cs @@ -135,11 +135,11 @@ public X500DistinguishedName GetDistinguishedName() // the extensions (OID, etc.). public enum X500NameElement { - Country = 0, - State = 1, - Locality = 2, - Organization = 3, - CommonName = 4, + Country = 0, + State = 1, + Locality = 2, + Organization = 3, + CommonName = 4, } public static class X500NameElementExtensions @@ -193,22 +193,22 @@ public static byte[] GetDerEncoding(this X500NameElement nameElement, string val public static byte[] GetOid(this X500NameElement nameElement) => nameElement switch { - X500NameElement.Country => new byte[] { 0x55, 0x04, 0x06 }, - X500NameElement.State => new byte[] { 0x55, 0x04, 0x08 }, - X500NameElement.Locality => new byte[] { 0x55, 0x04, 0x07 }, - X500NameElement.Organization => new byte[] { 0x55, 0x04, 0x0A }, - X500NameElement.CommonName => new byte[] { 0x55, 0x04, 0x03 }, + X500NameElement.Country => new byte[] { 0x55, 0x04, 0x06 }, + X500NameElement.State => new byte[] { 0x55, 0x04, 0x08 }, + X500NameElement.Locality => new byte[] { 0x55, 0x04, 0x07 }, + X500NameElement.Organization => new byte[] { 0x55, 0x04, 0x0A }, + X500NameElement.CommonName => new byte[] { 0x55, 0x04, 0x03 }, _ => throw new ArgumentException(X500NameBuilder.InvalidElementMessage), }; // Is the given length valid for the specified nameElement? public static bool IsValidValueLength(this X500NameElement nameElement, int length) => nameElement switch { - X500NameElement.Country => length == 2, - X500NameElement.State => (length > 0) && (length < 32), - X500NameElement.Locality => (length > 0) && (length < 32), - X500NameElement.Organization => (length > 0) && (length < 64), - X500NameElement.CommonName => (length > 0) && (length < 64), + X500NameElement.Country => length == 2, + X500NameElement.State => length > 0 && length < 32, + X500NameElement.Locality => length > 0 && length < 32, + X500NameElement.Organization => length > 0 && length < 64, + X500NameElement.CommonName => length > 0 && length < 64, _ => throw new ArgumentException(X500NameBuilder.InvalidElementMessage), }; } diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/PriorityOrderer.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/PriorityOrderer.cs index 86c34f8f..b12cb85b 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/PriorityOrderer.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/PriorityOrderer.cs @@ -33,7 +33,7 @@ public IEnumerable OrderTestCases( IEnumerable testCases) where TTestCase : ITestCase { - return testCases.OrderBy(GetOrder); + return testCases.OrderBy(GetOrder); } private static int GetOrder( diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/ReclaimTimeoutTests.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/ReclaimTimeoutTests.cs index f06e3e7c..401b39c8 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/ReclaimTimeoutTests.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/ReclaimTimeoutTests.cs @@ -15,16 +15,16 @@ using System; using System.Diagnostics; using System.Threading; +using Microsoft.Extensions.Logging; +using Serilog; +using Serilog.Core; +using Serilog.Events; using Xunit; using Yubico.YubiKey.Fido2; using Yubico.YubiKey.Otp; using Yubico.YubiKey.Piv; using Yubico.YubiKey.TestUtilities; - -using Microsoft.Extensions.Logging; -using Serilog; -using Serilog.Core; -using Serilog.Events; +using Log = Yubico.Core.Logging.Log; namespace Yubico.YubiKey { @@ -42,13 +42,13 @@ public class ReclaimTimeoutTests [Fact] public void SwitchingBetweenTransports_ForcesThreeSecondWait() { - using var log = new LoggerConfiguration() + using Logger? log = new LoggerConfiguration() .Enrich.With(new ThreadIdEnricher()) .WriteTo.Console( outputTemplate: "{Timestamp:HH:mm:ss.fffffff} [{Level}] ({ThreadId}) {Message}{NewLine}{Exception}") .CreateLogger(); - Core.Logging.Log.LoggerFactory = LoggerFactory.Create( + Log.LoggerFactory = LoggerFactory.Create( builder => builder .AddSerilog(log) .AddFilter(level => level >= LogLevel.Information)); diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Scp03/Commands/DeleteKeyCommandTests.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Scp03/Commands/DeleteKeyCommandTests.cs index 2b9aa588..cb5edba2 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Scp03/Commands/DeleteKeyCommandTests.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Scp03/Commands/DeleteKeyCommandTests.cs @@ -12,9 +12,8 @@ // See the License for the specific language governing permissions and // limitations under the License. -using System; -using Yubico.YubiKey.TestUtilities; using Xunit; +using Yubico.YubiKey.TestUtilities; namespace Yubico.YubiKey.Scp03.Commands { @@ -23,17 +22,17 @@ public class DeleteKeyCommandTests [Fact] public void DeleteKey_One_Succeeds() { - byte[] applicationId = new byte[] { + byte[] applicationId = { 0xA0, 0x00, 0x00, 0x01, 0x51, 0x00, 0x00, 0x00 }; - byte[] key1 = new byte[] { + byte[] key1 = { 0x33, 0xff, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0x00, 0xaa, 0xbb, 0xcc, 0xdd, }; - byte[] key2 = new byte[] { + byte[] key2 = { 0x33, 0xee, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0x00, 0xaa, 0xbb, 0xcc, 0xdd, 0xff, }; - byte[] key3 = new byte[] { + byte[] key3 = { 0x33, 0xdd, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0x00, 0xaa, 0xbb, 0xcc, 0xee, 0xff, 0x11, }; var currentKeys = new StaticKeys(key2, key1, key3) @@ -55,17 +54,17 @@ public void DeleteKey_One_Succeeds() [Fact] public void DeleteKey_Two_Succeeds() { - byte[] applicationId = new byte[] { + byte[] applicationId = { 0xA0, 0x00, 0x00, 0x01, 0x51, 0x00, 0x00, 0x00 }; - byte[] key1 = new byte[] { + byte[] key1 = { 0x33, 0xff, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0x00, 0xaa, 0xbb, 0xcc, 0xdd, }; - byte[] key2 = new byte[] { + byte[] key2 = { 0x33, 0xee, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0x00, 0xaa, 0xbb, 0xcc, 0xdd, 0xff, }; - byte[] key3 = new byte[] { + byte[] key3 = { 0x33, 0xdd, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0x00, 0xaa, 0xbb, 0xcc, 0xee, 0xff, 0x11, }; var currentKeys = new StaticKeys(key2, key1, key3) @@ -87,17 +86,17 @@ public void DeleteKey_Two_Succeeds() [Fact] public void DeleteKey_Three_Succeeds() { - byte[] applicationId = new byte[] { + byte[] applicationId = { 0xA0, 0x00, 0x00, 0x01, 0x51, 0x00, 0x00, 0x00 }; - byte[] key1 = new byte[] { + byte[] key1 = { 0x33, 0xff, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0x00, 0xaa, 0xbb, 0xcc, 0xdd, }; - byte[] key2 = new byte[] { + byte[] key2 = { 0x33, 0xee, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0x00, 0xaa, 0xbb, 0xcc, 0xdd, 0xff, }; - byte[] key3 = new byte[] { + byte[] key3 = { 0x33, 0xdd, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0x00, 0xaa, 0xbb, 0xcc, 0xee, 0xff, 0x11, }; var currentKeys = new StaticKeys(key2, key1, key3) diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Scp03/Commands/PutKeyCommandTests.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Scp03/Commands/PutKeyCommandTests.cs index 8f2f3393..814feaf0 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Scp03/Commands/PutKeyCommandTests.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Scp03/Commands/PutKeyCommandTests.cs @@ -13,8 +13,8 @@ // limitations under the License. using System; -using Yubico.YubiKey.TestUtilities; using Xunit; +using Yubico.YubiKey.TestUtilities; namespace Yubico.YubiKey.Scp03.Commands { @@ -23,16 +23,16 @@ public class PutKeyCommandTests [Fact] public void ChangeDefaultKey_Succeeds() { - byte[] key1 = new byte[] { + byte[] key1 = { 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0x00, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff }; - byte[] key2 = new byte[] { + byte[] key2 = { 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0x00, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff, 0x11 }; - byte[] key3 = new byte[] { + byte[] key3 = { 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0x00, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff, 0x11, 0x22 }; - byte[] applicationId = new byte[] { + byte[] applicationId = { 0xA0, 0x00, 0x00, 0x01, 0x51, 0x00, 0x00, 0x00 }; @@ -49,32 +49,32 @@ public void ChangeDefaultKey_Succeeds() PutKeyResponse rsp = connection!.SendCommand(cmd); Assert.Equal(ResponseStatus.Success, rsp.Status); ReadOnlyMemory checksum = rsp.GetData(); - bool isEqual = MemoryExtensions.SequenceEqual(checksum.Span, cmd.ExpectedChecksum.Span); + bool isEqual = checksum.Span.SequenceEqual(cmd.ExpectedChecksum.Span); Assert.True(isEqual); } [Fact] public void AddNewKeySet_Succeeds() { - byte[] key1 = new byte[] { + byte[] key1 = { 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0x00, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff }; - byte[] key2 = new byte[] { + byte[] key2 = { 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0x00, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff, 0x11 }; - byte[] key3 = new byte[] { + byte[] key3 = { 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0x00, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff, 0x11, 0x22 }; - byte[] newKey1 = new byte[] { + byte[] newKey1 = { 0xff, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0x00, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, }; - byte[] newKey2 = new byte[] { + byte[] newKey2 = { 0xee, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0x00, 0xaa, 0xbb, 0xcc, 0xdd, 0xff, 0x11 }; - byte[] newKey3 = new byte[] { + byte[] newKey3 = { 0xdd, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0x00, 0xaa, 0xbb, 0xcc, 0xee, 0xff, 0x11, 0x22 }; - byte[] applicationId = new byte[] { + byte[] applicationId = { 0xA0, 0x00, 0x00, 0x01, 0x51, 0x00, 0x00, 0x00 }; @@ -94,32 +94,32 @@ public void AddNewKeySet_Succeeds() PutKeyResponse rsp = connection!.SendCommand(cmd); Assert.Equal(ResponseStatus.Success, rsp.Status); ReadOnlyMemory checksum = rsp.GetData(); - bool isEqual = MemoryExtensions.SequenceEqual(checksum.Span, cmd.ExpectedChecksum.Span); + bool isEqual = checksum.Span.SequenceEqual(cmd.ExpectedChecksum.Span); Assert.True(isEqual); } [Fact] public void AddThirdKeySet_Succeeds() { - byte[] key1 = new byte[] { + byte[] key1 = { 0xff, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0x00, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, }; - byte[] key2 = new byte[] { + byte[] key2 = { 0xee, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0x00, 0xaa, 0xbb, 0xcc, 0xdd, 0xff, 0x11 }; - byte[] key3 = new byte[] { + byte[] key3 = { 0xdd, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0x00, 0xaa, 0xbb, 0xcc, 0xee, 0xff, 0x11, 0x22 }; - byte[] newKey1 = new byte[] { + byte[] newKey1 = { 0x33, 0xff, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0x00, 0xaa, 0xbb, 0xcc, 0xdd, }; - byte[] newKey2 = new byte[] { + byte[] newKey2 = { 0x33, 0xee, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0x00, 0xaa, 0xbb, 0xcc, 0xdd, 0xff, }; - byte[] newKey3 = new byte[] { + byte[] newKey3 = { 0x33, 0xdd, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0x00, 0xaa, 0xbb, 0xcc, 0xee, 0xff, 0x11, }; - byte[] applicationId = new byte[] { + byte[] applicationId = { 0xA0, 0x00, 0x00, 0x01, 0x51, 0x00, 0x00, 0x00 }; @@ -142,7 +142,7 @@ public void AddThirdKeySet_Succeeds() PutKeyResponse rsp = connection!.SendCommand(cmd); Assert.Equal(ResponseStatus.Success, rsp.Status); ReadOnlyMemory checksum = rsp.GetData(); - bool isEqual = MemoryExtensions.SequenceEqual(checksum.Span, cmd.ExpectedChecksum.Span); + bool isEqual = checksum.Span.SequenceEqual(cmd.ExpectedChecksum.Span); Assert.True(isEqual); } } diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Scp03/PutDeleteKeyTests.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Scp03/PutDeleteKeyTests.cs index 297f5740..01711754 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Scp03/PutDeleteKeyTests.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Scp03/PutDeleteKeyTests.cs @@ -18,15 +18,18 @@ namespace Yubico.YubiKey.Scp03 { + [TestCaseOrderer(PriorityOrderer.TypeName, PriorityOrderer.AssembyName)] + [Trait("Category", "Simple")] public class PutDeleteTests { [Fact] + [TestPriority(3)] public void PutKey_Succeeds() { using var staticKeys = new StaticKeys(); IYubiKeyDevice device = IntegrationTestDeviceEnumeration.GetTestDevice( Transport.SmartCard, - FirmwareVersion.V5_3_0); + minimumFirmwareVersion: FirmwareVersion.V5_3_0); using (var scp03Session = new Scp03Session(device, staticKeys)) { @@ -47,6 +50,7 @@ public void PutKey_Succeeds() } [Fact] + [TestPriority(3)] public void ReplaceKey_Succeeds() { using StaticKeys staticKeys = GetKeySet(2); @@ -63,6 +67,7 @@ public void ReplaceKey_Succeeds() } [Fact] + [TestPriority(0)] public void DeleteKey_Succeeds() { using StaticKeys staticKeys = GetKeySet(3); @@ -71,8 +76,8 @@ public void DeleteKey_Succeeds() FirmwareVersion.V5_3_0); using var scp03Session = new Scp03Session(device, staticKeys); - scp03Session.DeleteKeySet(1, false); - scp03Session.DeleteKeySet(2, false); + scp03Session.DeleteKeySet(1); + scp03Session.DeleteKeySet(2); scp03Session.DeleteKeySet(3, true); } @@ -87,13 +92,16 @@ public void DeleteKey_Succeeds() private StaticKeys GetKeySet1() { - var key1 = new ReadOnlyMemory(new byte[] { + var key1 = new ReadOnlyMemory(new byte[] + { 0x11, 0x11, 0x11, 0x11, 0x49, 0x2f, 0x4d, 0x09, 0x22, 0xec, 0x3d, 0xb4, 0x6b, 0x20, 0x94, 0x7a }); - var key2 = new ReadOnlyMemory(new byte[] { + var key2 = new ReadOnlyMemory(new byte[] + { 0x12, 0x12, 0x12, 0x12, 0x53, 0xB3, 0xE3, 0x78, 0x2A, 0x1D, 0xE5, 0xDC, 0x5A, 0xF4, 0xa6, 0x41 }); - var key3 = new ReadOnlyMemory(new byte[] { + var key3 = new ReadOnlyMemory(new byte[] + { 0x13, 0x13, 0x13, 0x13, 0x68, 0xDE, 0x7A, 0xB7, 0x74, 0x19, 0xBB, 0x7F, 0xB0, 0x55, 0x7d, 0x40 }); @@ -102,13 +110,16 @@ private StaticKeys GetKeySet1() private StaticKeys GetKeySet2() { - var key1 = new ReadOnlyMemory(new byte[] { + var key1 = new ReadOnlyMemory(new byte[] + { 0x21, 0x21, 0x21, 0x21, 0x20, 0x94, 0x7a, 0x49, 0x2f, 0x4d, 0x09, 0x22, 0xec, 0x3d, 0xb4, 0x6b }); - var key2 = new ReadOnlyMemory(new byte[] { + var key2 = new ReadOnlyMemory(new byte[] + { 0x22, 0x22, 0x22, 0x22, 0xDC, 0x5A, 0xF4, 0xa6, 0x41, 0x53, 0xB3, 0xE3, 0x78, 0x2A, 0x1D, 0xE5 }); - var key3 = new ReadOnlyMemory(new byte[] { + var key3 = new ReadOnlyMemory(new byte[] + { 0x23, 0x23, 0x23, 0x23, 0x7d, 0x40, 0x68, 0xDE, 0x7A, 0xB7, 0x74, 0x19, 0xBB, 0x7F, 0xB0, 0x55 }); @@ -120,13 +131,16 @@ private StaticKeys GetKeySet2() private StaticKeys GetKeySet3() { - var key1 = new ReadOnlyMemory(new byte[] { + var key1 = new ReadOnlyMemory(new byte[] + { 0x21, 0x21, 0x21, 0x21, 0x20, 0xDC, 0x5A, 0xF4, 0xa6, 0x41, 0x94, 0x7a, 0x49, 0x2f, 0x4d, 0x09 }); - var key2 = new ReadOnlyMemory(new byte[] { + var key2 = new ReadOnlyMemory(new byte[] + { 0x22, 0x22, 0x22, 0x22, 0x22, 0xec, 0x3d, 0xb4, 0x6b, 0x53, 0xB3, 0xE3, 0x78, 0x2A, 0x1D, 0xE5 }); - var key3 = new ReadOnlyMemory(new byte[] { + var key3 = new ReadOnlyMemory(new byte[] + { 0x23, 0x23, 0x23, 0x23, 0x7A, 0xB7, 0x74, 0x19, 0x7d, 0x40, 0x68, 0xDE, 0xBB, 0x7F, 0xB0, 0x55 }); diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Scp03/SimpleSessionTests.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Scp03/SimpleSessionTests.cs index 8bbc9e23..9adcf96d 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Scp03/SimpleSessionTests.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Scp03/SimpleSessionTests.cs @@ -14,16 +14,15 @@ using System; using Xunit; -using Yubico.YubiKey.TestUtilities; using Yubico.YubiKey.Piv; using Yubico.YubiKey.Piv.Commands; -using System.Net.NetworkInformation; +using Yubico.YubiKey.TestUtilities; namespace Yubico.YubiKey.Scp03 { public class SimpleSessionTests { - private readonly byte[] _pin = new byte[] { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36 }; + private readonly byte[] _pin = { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36 }; [Theory] [InlineData(StandardTestDevice.Fw5)] diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/TestPriorityAttribute.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/TestPriorityAttribute.cs index 51eaa259..a76ea858 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/TestPriorityAttribute.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/TestPriorityAttribute.cs @@ -16,7 +16,7 @@ namespace Yubico.YubiKey { - [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)] + [AttributeUsage(AttributeTargets.Method)] public class TestPriorityAttribute : Attribute { public int Priority { get; private set; } diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/U2f/CommandTests.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/U2f/CommandTests.cs index a69820af..86ddece7 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/U2f/CommandTests.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/U2f/CommandTests.cs @@ -14,11 +14,10 @@ using System; using System.Collections.Generic; -using System.Linq; +using Xunit; using Yubico.Core.Devices.Hid; using Yubico.PlatformInterop; using Yubico.YubiKey.U2f.Commands; -using Xunit; namespace Yubico.YubiKey.U2f { @@ -57,13 +56,9 @@ public void Dispose() } [Fact] + [Trait("Category", "Simple")] public void RunGetDeviceInfo() { - if (_fidoConnection is null) - { - return; - } - var cmd = new GetDeviceInfoCommand(); GetDeviceInfoResponse rsp = _fidoConnection.SendCommand(cmd); Assert.Equal(ResponseStatus.Success, rsp.Status); @@ -75,28 +70,18 @@ public void RunGetDeviceInfo() [Fact] public void RunSetDeviceInfo() { - if (_fidoConnection is null) - { - return; - } - var cmd = new SetDeviceInfoCommand(); Assert.Null(cmd.DeviceFlags); -// GetDeviceInfoResponse rsp = _fidoConnection.SendCommand(cmd); -// Assert.Equal(ResponseStatus.Success, rsp.Status); + // GetDeviceInfoResponse rsp = _fidoConnection.SendCommand(cmd); + // Assert.Equal(ResponseStatus.Success, rsp.Status); -// YubiKeyDeviceInfo getData = rsp.GetData(); -// Assert.False(getData.IsFipsSeries); + // YubiKeyDeviceInfo getData = rsp.GetData(); + // Assert.False(getData.IsFipsSeries); } [Fact] public void VerifyFipsMode() { - if (_fidoConnection is null) - { - return; - } - var cmd = new VerifyFipsModeCommand(); VerifyFipsModeResponse rsp = _fidoConnection.SendCommand(cmd); Assert.Equal(ResponseStatus.Success, rsp.Status); @@ -109,8 +94,8 @@ public void VerifyFipsMode() { foreach (HidDevice currentDevice in devices) { - if ((currentDevice.VendorId == 0x1050) && - (currentDevice.UsagePage == HidUsagePage.Fido)) + if (currentDevice.VendorId == 0x1050 && + currentDevice.UsagePage == HidUsagePage.Fido) { return currentDevice; } diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/U2f/PinTests.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/U2f/PinTests.cs index 0edea783..e9f7b8dc 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/U2f/PinTests.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/U2f/PinTests.cs @@ -14,14 +14,15 @@ using System; using System.Collections.Generic; -using Yubico.Core.Iso7816; +using Xunit; using Yubico.Core.Devices.Hid; +using Yubico.Core.Iso7816; using Yubico.PlatformInterop; using Yubico.YubiKey.U2f.Commands; -using Xunit; namespace Yubico.YubiKey.U2f { + [Trait("Category", "Elevated")] public class PinTests : IDisposable { private readonly FidoConnection _fidoConnection; @@ -59,18 +60,13 @@ public void Dispose() [Fact] public void SetPin_Succeeds() { - byte[] currentPin = new byte[] { + byte[] currentPin = { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36 }; - byte[] newPin = new byte[] { + byte[] newPin = { 0x41, 0x42, 0x43, 0x44, 0x45, 0x46 }; - if (_fidoConnection is null) - { - return; - } - var cmd = new GetDeviceInfoCommand(); GetDeviceInfoResponse rsp = _fidoConnection.SendCommand(cmd); Assert.Equal(ResponseStatus.Success, rsp.Status); @@ -103,38 +99,28 @@ public void SetPin_Succeeds() [Fact] public void InvalidPin_CorrectError() { - byte[] currentPin = new byte[] { + byte[] currentPin = { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36 }; - byte[] badPin = new byte[] { + byte[] badPin = { 0x41, 0x42, 0x43, 0x44 }; - if (_fidoConnection is null) - { - return; - } - var setCmd = new SetPinCommand(currentPin, badPin); SetPinResponse setRsp = _fidoConnection.SendCommand(setCmd); - Assert.NotEqual(ResponseStatus.Success, setRsp.Status); + Assert.Equal(ResponseStatus.Failed, setRsp.Status); } [Fact] public void VerifyPin_Succeeds() { - byte[] correctPin = new byte[] { + byte[] correctPin = { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36 }; - byte[] wrongPin = new byte[] { + byte[] wrongPin = { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37 }; - if (_fidoConnection is null) - { - return; - } - var cmd = new GetDeviceInfoCommand(); GetDeviceInfoResponse rsp = _fidoConnection.SendCommand(cmd); Assert.Equal(ResponseStatus.Success, rsp.Status); @@ -146,15 +132,15 @@ public void VerifyPin_Succeeds() } var vfyCmd = new VerifyPinCommand(correctPin); - VerifyPinResponse vfyRsp = _fidoConnection.SendCommand(vfyCmd); + VerifyPinResponse vfyRsp = _fidoConnection.SendCommand(vfyCmd); Assert.Equal(ResponseStatus.Success, vfyRsp.Status); vfyCmd = new VerifyPinCommand(wrongPin); - vfyRsp = _fidoConnection.SendCommand(vfyCmd); + vfyRsp = _fidoConnection.SendCommand(vfyCmd); Assert.Equal(ResponseStatus.Failed, vfyRsp.Status); vfyCmd = new VerifyPinCommand(correctPin); - vfyRsp = _fidoConnection.SendCommand(vfyCmd); + vfyRsp = _fidoConnection.SendCommand(vfyCmd); Assert.Equal(ResponseStatus.Success, vfyRsp.Status); } @@ -164,18 +150,18 @@ public void VerifyPin_Succeeds() // This test will make block the YubiKey's U2F application. The only way // to unblock is to reset, but once a U2F application has been reset, it // is not possible to put that YubiKey back into FIPS mode. - [Fact] - public void WrongPin_ThreeTimes() + [SkippableFact] + public void WrongPin_ThreeTimes() // Not sure how to run this test { - byte[] correctPin = new byte[] { + byte[] correctPin = { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36 }; - byte[] wrongPin = new byte[] { + byte[] wrongPin = { 0x41, 0x42, 0x43, 0x44, 0x45, 0x46 }; bool isValid = IsYubiKeyVersion4Fips(out bool isFipsMode); - Assert.True(isValid); + Skip.IfNot(isValid); if (!isFipsMode) { isValid = SetU2fPin(correctPin); @@ -183,7 +169,7 @@ public void WrongPin_ThreeTimes() } var vfyCmd = new VerifyPinCommand(correctPin); - VerifyPinResponse vfyRsp = _fidoConnection.SendCommand(vfyCmd); + VerifyPinResponse vfyRsp = _fidoConnection.SendCommand(vfyCmd); Assert.Equal(ResponseStatus.Success, vfyRsp.Status); // Verify with the wrong PIN 3 times. @@ -191,15 +177,15 @@ public void WrongPin_ThreeTimes() // The third time it should be // SWConstants.AuthenticationMethodBlocked. vfyCmd = new VerifyPinCommand(wrongPin); - vfyRsp = _fidoConnection.SendCommand(vfyCmd); + vfyRsp = _fidoConnection.SendCommand(vfyCmd); Assert.Equal(SWConstants.VerifyFail, vfyRsp.StatusWord); vfyCmd = new VerifyPinCommand(wrongPin); - vfyRsp = _fidoConnection.SendCommand(vfyCmd); + vfyRsp = _fidoConnection.SendCommand(vfyCmd); Assert.Equal(SWConstants.VerifyFail, vfyRsp.StatusWord); vfyCmd = new VerifyPinCommand(wrongPin); - vfyRsp = _fidoConnection.SendCommand(vfyCmd); + vfyRsp = _fidoConnection.SendCommand(vfyCmd); Assert.Equal(SWConstants.AuthenticationMethodBlocked, vfyRsp.StatusWord); // At this point, the YubiKey's U2F application is blocked and the @@ -210,11 +196,6 @@ private bool IsYubiKeyVersion4Fips(out bool isFipsMode) { isFipsMode = false; - if (_fidoConnection is null) - { - return false; - } - var cmd = new GetDeviceInfoCommand(); GetDeviceInfoResponse rsp = _fidoConnection.SendCommand(cmd); if (rsp.Status != ResponseStatus.Success) @@ -223,9 +204,9 @@ private bool IsYubiKeyVersion4Fips(out bool isFipsMode) } YubiKeyDeviceInfo getData = rsp.GetData(); - if ((!getData.IsFipsSeries) || - (getData.FirmwareVersion >= new FirmwareVersion(5, 0, 0)) || - (getData.FirmwareVersion < new FirmwareVersion(4, 0, 0))) + if (!getData.IsFipsSeries || + getData.FirmwareVersion >= new FirmwareVersion(5) || + getData.FirmwareVersion < new FirmwareVersion(4)) { return false; } diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/U2f/Registration.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/U2f/Registration.cs index 9a08c2a6..750ddafd 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/U2f/Registration.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/U2f/Registration.cs @@ -28,7 +28,7 @@ public void RegisterCredential_BasicTest(StandardTestDevice testDeviceType) using (var u2fSession = new U2fSession(testDevice)) { - u2fSession.KeyCollector = (k) => k.Request switch + u2fSession.KeyCollector = k => k.Request switch { KeyEntryRequest.TouchRequest => true, _ => throw new NotSupportedException("Test requested a key that is not supported by this test case.") diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/U2f/SessionPinTests.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/U2f/SessionPinTests.cs index abb65af7..9e900d21 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/U2f/SessionPinTests.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/U2f/SessionPinTests.cs @@ -15,10 +15,8 @@ using System; using System.Collections.Generic; using System.Linq; -using Yubico.Core.Devices.Hid; -using Yubico.PlatformInterop; -using Yubico.YubiKey.U2f.Commands; using Xunit; +using Yubico.PlatformInterop; namespace Yubico.YubiKey.U2f { @@ -63,13 +61,13 @@ public void ChangePin_Succeeds() [Fact] public void TryChangePin_NoCollector_Succeeds() { - byte[] currentPin = new byte[] { + byte[] currentPin = { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36 }; - byte[] newPin = new byte[] { + byte[] newPin = { 0x41, 0x42, 0x43, 0x44, 0x45, 0x46 }; - byte[] shortPin = new byte[] { + byte[] shortPin = { 0x61, 0x62, 0x63, 0x64, 0x65 }; @@ -109,13 +107,13 @@ public void VerifyPin_Succeeds() [Fact] public void TryVerifyPin_NoCollector_Succeeds() { - byte[] currentPin = new byte[] { + byte[] currentPin = { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36 }; - byte[] wrongPin = new byte[] { + byte[] wrongPin = { 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18 }; - byte[] shortPin = new byte[] { + byte[] shortPin = { 0x61, 0x62, 0x63, 0x64, 0x65 }; diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/U2f/SessionRegisterTests.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/U2f/SessionRegisterTests.cs index 5e8b5445..0ff5da51 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/U2f/SessionRegisterTests.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/U2f/SessionRegisterTests.cs @@ -15,10 +15,9 @@ using System; using System.Collections.Generic; using System.Linq; -using Yubico.Core.Devices.Hid; +using Xunit; using Yubico.PlatformInterop; using Yubico.YubiKey.U2f.Commands; -using Xunit; namespace Yubico.YubiKey.U2f { @@ -74,8 +73,8 @@ public void RegisterFips_Succeeds() appId, clientDataHash, new TimeSpan(0, 0, 5), out RegistrationData? regDataQ); Assert.True(isValid); -// RegistrationData regDataQ = u2fSession.Register( -// appId, clientDataHash, TimeSpan.Zero); + // RegistrationData regDataQ = u2fSession.Register( + // appId, clientDataHash, TimeSpan.Zero); Assert.NotNull(regDataQ); @@ -84,7 +83,7 @@ public void RegisterFips_Succeeds() return; } - var regData = (RegistrationData)regDataQ; + RegistrationData regData = regDataQ; bool isVerified = regData.VerifySignature(appId, clientDataHash); Assert.True(isVerified); diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/U2f/SetDeviceInfoTests.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/U2f/SetDeviceInfoTests.cs index 7facdee1..b1766b40 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/U2f/SetDeviceInfoTests.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/U2f/SetDeviceInfoTests.cs @@ -14,12 +14,10 @@ using System; using System.Collections.Generic; -using System.Linq; +using Xunit; using Yubico.Core.Devices.Hid; using Yubico.PlatformInterop; using Yubico.YubiKey.U2f.Commands; -using Xunit; -using Yubico.Core.Iso7816; namespace Yubico.YubiKey.U2f { @@ -61,8 +59,8 @@ public void Dispose() { foreach (HidDevice currentDevice in devices) { - if ((currentDevice.VendorId == 0x1050) && - (currentDevice.UsagePage == HidUsagePage.Fido)) + if (currentDevice.VendorId == 0x1050 && + currentDevice.UsagePage == HidUsagePage.Fido) { return currentDevice; } @@ -74,8 +72,10 @@ public void Dispose() [Fact] public void SetCRTimeout_Succeeds() { - var cmd = new SetDeviceInfoCommand(); - cmd.ChallengeResponseTimeout = 0x20; + var cmd = new SetDeviceInfoCommand + { + ChallengeResponseTimeout = 0x20 + }; SetDeviceInfoResponse rsp = _fidoConnection.SendCommand(cmd); Assert.Equal(ResponseStatus.Success, rsp.Status); @@ -91,21 +91,23 @@ public void SetCRTimeout_Succeeds() [Fact] public void SetLockCode_Succeeds() { - byte[] newCode = new byte[] { + byte[] newCode = { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48 }; - byte[] wrongCode = new byte[] { + byte[] wrongCode = { 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58 }; - byte[] clearCode = new byte[] { + byte[] clearCode = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; - var cmd = new SetDeviceInfoCommand(); - cmd.ChallengeResponseTimeout = 0x21; + var cmd = new SetDeviceInfoCommand + { + ChallengeResponseTimeout = 0x21 + }; SetDeviceInfoResponse rsp = _fidoConnection.SendCommand(cmd); Assert.Equal(ResponseStatus.Success, rsp.Status); @@ -114,8 +116,10 @@ public void SetLockCode_Succeeds() rsp = _fidoConnection.SendCommand(cmd); Assert.Equal(ResponseStatus.Success, rsp.Status); - cmd = new SetDeviceInfoCommand(); - cmd.ChallengeResponseTimeout = 0x22; + cmd = new SetDeviceInfoCommand + { + ChallengeResponseTimeout = 0x22 + }; rsp = _fidoConnection.SendCommand(cmd); Assert.NotEqual(ResponseStatus.Success, rsp.Status); @@ -149,8 +153,10 @@ public void SetLockCode_Succeeds() public void SetLegacyCRTimeout_Succeeds() { var cmd = new SetLegacyDeviceConfigCommand( - YubiKeyCapabilities.Ccid, 0x21, true, 255); - cmd.YubiKeyInterfaces = YubiKeyCapabilities.All; + YubiKeyCapabilities.Ccid, 0x21, true, 255) + { + YubiKeyInterfaces = YubiKeyCapabilities.All + }; YubiKeyResponse rsp = _fidoConnection.SendCommand(cmd); Assert.Equal(ResponseStatus.Success, rsp.Status); diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/U2f/SimpleU2fKeyCollector.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/U2f/SimpleU2fKeyCollector.cs index 7cd53ed7..617b0402 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/U2f/SimpleU2fKeyCollector.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/U2f/SimpleU2fKeyCollector.cs @@ -23,18 +23,16 @@ namespace Yubico.YubiKey.U2f // changed to 0x39. public class SimpleU2fKeyCollector { - private readonly ReadOnlyMemory _firstPin = new ReadOnlyMemory(new byte[] { + private readonly ReadOnlyMemory _firstPin = new ReadOnlyMemory(new byte[] + { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36 }); - private readonly ReadOnlyMemory _secondPin = new ReadOnlyMemory(new byte[] { + private readonly ReadOnlyMemory _secondPin = new ReadOnlyMemory(new byte[] + { 0x41, 0x42, 0x43, 0x44, 0x45, 0x46 }); - public ReadOnlyMemory CurrentPin { get; private set; } - - public ReadOnlyMemory NewPin { get; private set; } - // If the caller sets the input arg to true, then the YubiKey's U2F PIN // is alreadys set. So the current PIN is "123456" and the new PIN is // "ABCDEF" @@ -56,6 +54,10 @@ public SimpleU2fKeyCollector(bool isU2fPinSet) } } + public ReadOnlyMemory CurrentPin { get; private set; } + + public ReadOnlyMemory NewPin { get; private set; } + public bool SimpleU2fKeyCollectorDelegate(KeyEntryData keyEntryData) { if (keyEntryData is null) @@ -63,7 +65,7 @@ public bool SimpleU2fKeyCollectorDelegate(KeyEntryData keyEntryData) return false; } - if (keyEntryData.IsRetry == true) + if (keyEntryData.IsRetry) { return false; } diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/U2f/SimpleU2fTests.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/U2f/SimpleU2fTests.cs index f8fc4d67..9424cadf 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/U2f/SimpleU2fTests.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/U2f/SimpleU2fTests.cs @@ -15,11 +15,11 @@ using System; using System.Collections.Generic; using System.Linq; +using Xunit; using Yubico.Core.Devices.Hid; +using Yubico.Core.Iso7816; using Yubico.PlatformInterop; using Yubico.YubiKey.U2f.Commands; -using Xunit; -using Yubico.Core.Iso7816; namespace Yubico.YubiKey.U2f { @@ -83,7 +83,7 @@ public void U2fHid_CommandIns0x77_ReturnsInvalidCommand() HidDevice deviceToUse = GetFidoHid(devices) ?? throw new InvalidOperationException(); FidoConnection connection = new FidoConnection(deviceToUse) ?? throw new InvalidOperationException(); - CommandApdu cmdApdu = new CommandApdu() + CommandApdu cmdApdu = new CommandApdu { Ins = 0x77, }; @@ -103,7 +103,7 @@ public void U2fHid_U2fInitNoData_ReturnsInvalidDataLength() HidDevice deviceToUse = GetFidoHid(devices) ?? throw new InvalidOperationException(); FidoConnection connection = new FidoConnection(deviceToUse) ?? throw new InvalidOperationException(); - CommandApdu cmdApdu = new CommandApdu() + CommandApdu cmdApdu = new CommandApdu { Ins = 0x06, }; @@ -150,8 +150,8 @@ public void GetProtocolVersion_Succeeds() } [Theory] - [InlineData(new byte[]{ })] - [InlineData(new byte[]{ 0x01, 0x02, 0x03 })] + [InlineData(new byte[] { })] + [InlineData(new byte[] { 0x01, 0x02, 0x03 })] public void EchoCommand_GetCorrectData(ReadOnlyMemory sendData) { if (SdkPlatformInfo.OperatingSystem == SdkPlatform.Windows) @@ -175,21 +175,21 @@ public void EchoCommand_GetCorrectData(ReadOnlyMemory sendData) IYubiKeyConnection connection = new FidoConnection(deviceToUse!); Assert.NotNull(connection); - + EchoCommand echoCommand = new EchoCommand(sendData); EchoResponse echoResponse = connection.SendCommand(echoCommand); ReadOnlyMemory echoData = echoResponse.GetData(); - + Assert.True(echoCommand.Data.Span.SequenceEqual(echoData.Span)); } - + private static HidDevice? GetFidoHid(IEnumerable devices) { foreach (HidDevice currentDevice in devices) { - if ((currentDevice.VendorId == 0x1050) && - (currentDevice.UsagePage == HidUsagePage.Fido)) + if (currentDevice.VendorId == 0x1050 && + currentDevice.UsagePage == HidUsagePage.Fido) { return currentDevice; } diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/U2f/U2fCommandTests.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/U2f/U2fCommandTests.cs index b1c05adc..347c4a2e 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/U2f/U2fCommandTests.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/U2f/U2fCommandTests.cs @@ -14,11 +14,10 @@ using System; using System.Collections.Generic; -using System.Linq; +using Xunit; using Yubico.Core.Devices.Hid; using Yubico.PlatformInterop; using Yubico.YubiKey.U2f.Commands; -using Xunit; namespace Yubico.YubiKey.U2f { @@ -56,12 +55,7 @@ public U2fCommandTests() [Fact] public void RegisterAndAuth_Succeeds() { - if (_fidoConnection is null) - { - return; - } - - byte[] pin = new byte[] { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36 }; + byte[] pin = { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36 }; var vfyPinCmd = new VerifyPinCommand(pin); VerifyPinResponse vfyPinRsp = _fidoConnection.SendCommand(vfyPinCmd); Assert.Equal(ResponseStatus.Success, vfyPinRsp.Status); @@ -127,8 +121,8 @@ public void Auth_Succeeds() { foreach (HidDevice currentDevice in devices) { - if ((currentDevice.VendorId == 0x1050) && - (currentDevice.UsagePage == HidUsagePage.Fido)) + if (currentDevice.VendorId == 0x1050 && + currentDevice.UsagePage == HidUsagePage.Fido) { return currentDevice; } diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/YubiHsmAuth/SessionCredentialTests.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/YubiHsmAuth/SessionCredentialTests.cs index bb50e14c..aa5ba1f4 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/YubiHsmAuth/SessionCredentialTests.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/YubiHsmAuth/SessionCredentialTests.cs @@ -222,7 +222,7 @@ public void TryAddCredentialKeyCollector_MgmtKeyRetry_AppContainsNewCred() // Preconditions IYubiKeyDevice testDevice = YhaTestUtilities.GetCleanDevice(); - SimpleKeyCollector simpleKeyCollector = new SimpleKeyCollector() + SimpleKeyCollector simpleKeyCollector = new SimpleKeyCollector { // Start with the incorrect management key, forcing a retry UseDefaultValue = false, diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/YubiHsmAuth/SessionGetAes128SessionKeysTests.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/YubiHsmAuth/SessionGetAes128SessionKeysTests.cs index a58938eb..174fa656 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/YubiHsmAuth/SessionGetAes128SessionKeysTests.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/YubiHsmAuth/SessionGetAes128SessionKeysTests.cs @@ -23,6 +23,7 @@ public class SessionGetAes128SessionKeysTests #region NonKeyCollector #region password [Fact] + [Trait("Category", "FirmwareOrHardwareMissmatch")] public void GetAes128SessionKeys_TouchNotRequired_ReturnsTrueAndSessionKeys() { // Preconditions @@ -48,6 +49,7 @@ public void GetAes128SessionKeys_TouchNotRequired_ReturnsTrueAndSessionKeys() } [Fact] + [Trait("Category", "Flaky")] public void GetAes128SessionKeys_WrongCredPassword_ThrowsSecurityException() { // Preconditions @@ -74,6 +76,7 @@ void getSessionKeys() => yubiHsmAuthSession.GetAes128SessionKeys( // It's recommended to use a debug break point in either the // key collector or GetAes128SessionKeys(...) so that you're // aware of when touch is about to be expected. + [Trait("Category", "RequiresStepDebug")] [Fact(Skip = "Requires user interaction")] public void GetAes128SessionKeys_TouchRequired_ReturnsSessionKeys() { diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/YubiHsmAuth/SessionManagementKeyTests.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/YubiHsmAuth/SessionManagementKeyTests.cs index 5b0f611f..3f387663 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/YubiHsmAuth/SessionManagementKeyTests.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/YubiHsmAuth/SessionManagementKeyTests.cs @@ -77,7 +77,7 @@ public void TryChangeManagementKey_ValidKeys_ReturnsTrue() IYubiKeyDevice testDevice = YhaTestUtilities.GetCleanDevice(); bool mgmtKeyChanged = false; - + using (var yubiHsmAuthSession = new YubiHsmAuthSession(testDevice)) { // Test @@ -285,7 +285,7 @@ public void TryChangeMgmtKeyKeyCollector_WrongCurrentKey_RetrySuccess() { // Preconditions IYubiKeyDevice testDevice = YhaTestUtilities.GetCleanDevice(); - SimpleKeyCollector keyCollector = new SimpleKeyCollector() + SimpleKeyCollector keyCollector = new SimpleKeyCollector { UseDefaultValue = false, }; diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/YubiHsmAuth/SimpleKeyCollector.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/YubiHsmAuth/SimpleKeyCollector.cs index c4b5ffb0..ce0827bf 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/YubiHsmAuth/SimpleKeyCollector.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/YubiHsmAuth/SimpleKeyCollector.cs @@ -13,7 +13,6 @@ // limitations under the License. using System; -using System.Threading; namespace Yubico.YubiKey.YubiHsmAuth { diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/YubiHsmAuth/YhaTestUtilities.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/YubiHsmAuth/YhaTestUtilities.cs index 629ca24a..8c5c63e9 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/YubiHsmAuth/YhaTestUtilities.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/YubiHsmAuth/YhaTestUtilities.cs @@ -12,6 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. +using System.Collections.Generic; using System.Linq; using Yubico.YubiKey.TestUtilities; @@ -24,7 +25,7 @@ namespace Yubico.YubiKey.YubiHsmAuth /// public class YhaTestUtilities { - public static readonly FirmwareVersion MinimumFirmwareVersion = new FirmwareVersion(5, 4, 3); + private static readonly FirmwareVersion MinimumFirmwareVersion = new FirmwareVersion(5, 4, 3); #region default public static readonly byte[] DefaultMgmtKey = @@ -39,7 +40,7 @@ public class YhaTestUtilities public static readonly string DefaultCredLabel = "abc"; public static readonly bool DefaultCredTouchRequired = false; - + public static readonly byte[] DefaultHostChallenge = new byte[8] { 0, 1, 2, 3, 4, 5, 6, 7 }; public static readonly byte[] DefaultHsmDeviceChallenge = @@ -100,14 +101,13 @@ public class YhaTestUtilities /// into a known "control" state for performing integration /// tests with the YubiHSM Auth application. /// - public static IYubiKeyDevice GetCleanDevice(FirmwareVersion fwVersion) + private static IYubiKeyDevice GetCleanDevice(FirmwareVersion fwVersion) { - var testDevices = IntegrationTestDeviceEnumeration.GetTestDevices(); + IList? testDevices = IntegrationTestDeviceEnumeration.GetTestDevices(); IYubiKeyDevice testDevice = testDevices - .Where(d => - d.FirmwareVersion == fwVersion - && d.SerialNumber.HasValue) - .First(); + .First(d => + d.FirmwareVersion >= fwVersion && + d.SerialNumber.HasValue); testDevice = DeviceReset.EnableAllCapabilities(testDevice); diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/YubiHsmAuth/YubiKeyDeviceYubiHsmAuth.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/YubiHsmAuth/YubiKeyDeviceYubiHsmAuth.cs index 5d0c0d52..7667a52a 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/YubiHsmAuth/YubiKeyDeviceYubiHsmAuth.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/YubiHsmAuth/YubiKeyDeviceYubiHsmAuth.cs @@ -12,7 +12,6 @@ // See the License for the specific language governing permissions and // limitations under the License. -using System; using Xunit; using Yubico.YubiKey.TestUtilities; diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/YubiKeyDeviceTests.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/YubiKeyDeviceTests.cs index 2e345a0e..5cff415e 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/YubiKeyDeviceTests.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/YubiKeyDeviceTests.cs @@ -15,10 +15,12 @@ using System; using System.Collections.Generic; using Xunit; +using Yubico.YubiKey.Management.Commands; using Yubico.YubiKey.TestUtilities; namespace Yubico.YubiKey { + [Trait("Category", "RequiresStepDebug")] // Timing issues, may need to step with debugger public class YubiKeyDeviceTests { private static readonly byte[] LockCodeAllZero = new byte[16]; @@ -158,7 +160,7 @@ private bool TryGetSkyDevice(out IYubiKeyDevice skyDevice) return false; } - [Theory] + [SkippableTheory(typeof(DeviceNotFoundException))] [InlineData(StandardTestDevice.Fw5)] [InlineData(StandardTestDevice.Fw5Fips)] public void SetEnabledNfcCapabilities_DisableFido2_OnlyFido2Disabled( @@ -177,7 +179,7 @@ public void SetEnabledNfcCapabilities_DisableFido2_OnlyFido2Disabled( Assert.Equal(desiredCapabilities, testDevice.EnabledNfcCapabilities); } - [Theory] + [SkippableTheory(typeof(DeviceNotFoundException))] [InlineData(StandardTestDevice.Fw5)] [InlineData(StandardTestDevice.Fw5Fips)] public void SetEnabledUsbCapabilities_EnableFido2OverOtp_Fido2AndOtpEnabled( @@ -202,7 +204,7 @@ public void SetEnabledUsbCapabilities_EnableFido2OverOtp_Fido2AndOtpEnabled( Assert.Equal(desiredCapabilities, testDevice.EnabledUsbCapabilities); } - [Theory] + [SkippableTheory(typeof(DeviceNotFoundException))] [InlineData(StandardTestDevice.Fw5)] [InlineData(StandardTestDevice.Fw5Fips)] public void SetEnabledUsbCapabilities_DisableFido2_OnlyFido2Disabled( @@ -221,7 +223,7 @@ public void SetEnabledUsbCapabilities_DisableFido2_OnlyFido2Disabled( Assert.Equal(desiredCapabilities, testDevice.EnabledUsbCapabilities); } - [Theory] + [SkippableTheory(typeof(DeviceNotFoundException))] [InlineData(StandardTestDevice.Fw5)] [InlineData(StandardTestDevice.Fw5Fips)] public void SetChallengeResponseTimeout_255seconds_ValueSetTo255( @@ -238,7 +240,7 @@ public void SetChallengeResponseTimeout_255seconds_ValueSetTo255( Assert.Equal(expectedTimeout, testDevice.ChallengeResponseTimeout); } - [Theory] + [SkippableTheory(typeof(DeviceNotFoundException))] [InlineData(StandardTestDevice.Fw5)] [InlineData(StandardTestDevice.Fw5Fips)] public void SetChallengeResponseTimeout_ZeroSeconds_DefaultValueSet( @@ -256,7 +258,7 @@ public void SetChallengeResponseTimeout_ZeroSeconds_DefaultValueSet( Assert.Equal(expectedTimeout, testDevice.ChallengeResponseTimeout); } - [Theory] + [SkippableTheory(typeof(DeviceNotFoundException))] [InlineData(StandardTestDevice.Fw5, ushort.MinValue)] [InlineData(StandardTestDevice.Fw5, ushort.MaxValue)] [InlineData(StandardTestDevice.Fw5Fips, ushort.MinValue)] @@ -279,7 +281,7 @@ public void SetAutoEjectTimeout_LimitValues_SetCorrectly( Assert.Equal(expectedTimeout, testDevice.AutoEjectTimeout); } - [Theory] + [SkippableTheory(typeof(DeviceNotFoundException))] [InlineData(StandardTestDevice.Fw5)] [InlineData(StandardTestDevice.Fw5Fips)] public void SetDeviceFlags_RemoteWakeupAndTouchEject_BothFlagsSet( @@ -296,7 +298,7 @@ public void SetDeviceFlags_RemoteWakeupAndTouchEject_BothFlagsSet( Assert.Equal(expectedDeviceFlags, testDevice.DeviceFlags); } - [Theory] + [SkippableTheory(typeof(DeviceNotFoundException))] [InlineData(StandardTestDevice.Fw5)] [InlineData(StandardTestDevice.Fw5Fips)] public void LockConfiguration_ValidLockCode_DeviceIsLocked(StandardTestDevice testDeviceType) @@ -311,7 +313,7 @@ public void LockConfiguration_ValidLockCode_DeviceIsLocked(StandardTestDevice te Assert.True(testDevice.ConfigurationLocked); } - [Theory] + [SkippableTheory(typeof(DeviceNotFoundException))] [InlineData(StandardTestDevice.Fw5)] [InlineData(StandardTestDevice.Fw5Fips)] public void LockConfiguration_SetLockCodeOnLockedDevice_ThrowsException( @@ -332,7 +334,7 @@ public void LockConfiguration_SetLockCodeOnLockedDevice_ThrowsException( () => testDevice.LockConfiguration(TestLockCode)); } - [Theory] + [SkippableTheory(typeof(DeviceNotFoundException))] [InlineData(StandardTestDevice.Fw5)] [InlineData(StandardTestDevice.Fw5Fips)] public void UnlockConfiguration_CorrectLockCode_DeviceNotLocked( @@ -354,7 +356,7 @@ public void UnlockConfiguration_CorrectLockCode_DeviceNotLocked( Assert.False(testDevice.ConfigurationLocked); } - [Theory] + [SkippableTheory(typeof(DeviceNotFoundException))] [InlineData(StandardTestDevice.Fw5)] [InlineData(StandardTestDevice.Fw5Fips)] public void UnlockConfiguration_IncorrectLockCode_ThrowsException( @@ -374,7 +376,7 @@ public void UnlockConfiguration_IncorrectLockCode_ThrowsException( () => testDevice.UnlockConfiguration(LockCodeAllZero)); } - [Theory] + [SkippableTheory(typeof(DeviceNotFoundException))] [InlineData(StandardTestDevice.Fw5)] [InlineData(StandardTestDevice.Fw5Fips)] public void UnlockConfiguration_AllZeroLockCodeOnUnlockedDevice_CommandSuccessful( @@ -387,7 +389,7 @@ public void UnlockConfiguration_AllZeroLockCodeOnUnlockedDevice_CommandSuccessfu testDevice.UnlockConfiguration(LockCodeAllZero); } - [Theory] + [SkippableTheory(typeof(DeviceNotFoundException))] [InlineData(StandardTestDevice.Fw5)] [InlineData(StandardTestDevice.Fw5Fips)] public void UnlockConfiguration_NonZeroLockCodeOnUnlockedDevice_ThrowsException( @@ -466,7 +468,7 @@ private static IYubiKeyDevice ResetDeviceInfo(IYubiKeyDevice testDevice) if (testDevice.FirmwareVersion.Major >= 5) { - var baseCommand = new Management.Commands.SetDeviceInfoCommand + var baseCommand = new SetDeviceInfoCommand { EnabledNfcCapabilities = YubiKeyCapabilities.All, EnabledUsbCapabilities = YubiKeyCapabilities.All, @@ -488,7 +490,7 @@ private static IYubiKeyDevice ResetDeviceInfo(IYubiKeyDevice testDevice) } else { - var baseCommand = new Management.Commands.SetLegacyDeviceConfigCommand( + var baseCommand = new SetLegacyDeviceConfigCommand( YubiKeyCapabilities.All, 0, false, @@ -509,13 +511,13 @@ private static IYubiKeyDevice ResetDeviceInfo(IYubiKeyDevice testDevice) private static IYubiKeyResponse SendConfiguration( IYubiKeyDevice yubiKey, - Management.Commands.SetDeviceInfoBaseCommand baseCommand) + SetDeviceInfoBaseCommand baseCommand) { IYubiKeyCommand command; if (yubiKey.TryConnect(YubiKeyApplication.Management, out IYubiKeyConnection? connection)) { - command = new Management.Commands.SetDeviceInfoCommand(baseCommand); + command = new SetDeviceInfoCommand(baseCommand); } else if (yubiKey.TryConnect(YubiKeyApplication.Otp, out connection)) { @@ -534,13 +536,13 @@ private static IYubiKeyResponse SendConfiguration( private static IYubiKeyResponse SendConfiguration( IYubiKeyDevice yubiKey, - Management.Commands.SetLegacyDeviceConfigBase baseCommand) + SetLegacyDeviceConfigBase baseCommand) { IYubiKeyCommand command; if (yubiKey.TryConnect(YubiKeyApplication.Management, out IYubiKeyConnection? connection)) { - command = new Management.Commands.SetLegacyDeviceConfigCommand(baseCommand); + command = new SetLegacyDeviceConfigCommand(baseCommand); } else if (yubiKey.TryConnect(YubiKeyApplication.Otp, out connection)) { diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/YubiKeyTests.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/YubiKeyTests.cs index 5fa994fc..83bd947e 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/YubiKeyTests.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/YubiKeyTests.cs @@ -21,6 +21,7 @@ namespace Yubico.YubiKey { + [Trait("Category", "RequiresSetup")] public class YubiKeyTests { private readonly ITestOutputHelper _testOutputHelper; @@ -39,7 +40,7 @@ public void GetYubiKeys_NoneTransport_ThrowsArgumentException() [Fact] public void GetYubiKeys_ExplicitAllTransports_MoreThanOneConnectedKey() { - var keys = YubiKeyDevice.FindByTransport(Transport.All).ToList(); + var keys = YubiKeyDevice.FindByTransport().ToList(); foreach (IYubiKeyDevice key in keys) { @@ -55,7 +56,7 @@ public void GetYubiKeys_ExplicitAllTransports_MoreThanOneConnectedKey() // Good test for checking matching logic. public void GetYubiKeys_ExplicitAllTransports_OneConnectedKey() { - var keys = YubiKeyDevice.FindByTransport(Transport.All).ToList(); + var keys = YubiKeyDevice.FindByTransport().ToList(); foreach (IYubiKeyDevice key in keys) { @@ -194,8 +195,8 @@ public void GetYubiKeys_SingleTransport_RapidSwitching() int numberOfRounds = 40; var rand = new Random(); - var transportValues = - new Transport[] { /*Transport.HidFido,*/ Transport.HidKeyboard, Transport.SmartCard }; + Transport[] transportValues = + new[] { /*Transport.HidFido,*/ Transport.HidKeyboard, Transport.SmartCard }; var transportTestValues = new Transport[numberOfRounds]; for (int i = 0; i < transportTestValues.Length; i++) @@ -216,7 +217,7 @@ public void GetYubiKeys_SingleTransport_RapidSwitching() sw.Restart(); keys = YubiKeyDevice.FindByTransport(ct).ToList(); sw.Stop(); - _testOutputHelper.WriteLine($"\t({keys.Count}) -{sw.ElapsedMilliseconds, 5}ms"); + _testOutputHelper.WriteLine($"\t({keys.Count}) -{sw.ElapsedMilliseconds,5}ms"); } } } diff --git a/Yubico.YubiKey/tests/sandbox/Plugins/DavidPlugin.cs b/Yubico.YubiKey/tests/sandbox/Plugins/DavidPlugin.cs index 249b2e90..e882c37b 100644 --- a/Yubico.YubiKey/tests/sandbox/Plugins/DavidPlugin.cs +++ b/Yubico.YubiKey/tests/sandbox/Plugins/DavidPlugin.cs @@ -974,10 +974,10 @@ private bool SessionAppMethods() Output.WriteLine(); Output.WriteLine("Attempting to get list of credentials..."); - var creds = yhaSession.ListCredentials(); + IReadOnlyList? creds = yhaSession.ListCredentials(); Output.WriteLine($"{creds.Count} credentials found."); int credLineCount = 1; - foreach (var cred in creds) + foreach (CredentialRetryPair? cred in creds) { Output.WriteLine($"{credLineCount++}) {cred.Credential.Label}, retries = {cred.Retries}"); } @@ -1073,7 +1073,7 @@ private bool SessionAppMethods() creds = yhaSession.ListCredentials(); Output.WriteLine($"{creds.Count} credentials found."); credLineCount = 1; - foreach (var cred in creds) + foreach (CredentialRetryPair? cred in creds) { Output.WriteLine($"{credLineCount++}) {cred.Credential.Label}, retries = {cred.Retries}"); } @@ -1095,7 +1095,7 @@ private bool SessionAppMethods() creds = yhaSession.ListCredentials(); Output.WriteLine($"{creds.Count} credentials found."); credLineCount = 1; - foreach (var cred in creds) + foreach (CredentialRetryPair? cred in creds) { Output.WriteLine($"{credLineCount++}) {cred.Credential.Label}, retries = {cred.Retries}"); } diff --git a/Yubico.YubiKey/tests/sandbox/Plugins/EnumeratePlugin.cs b/Yubico.YubiKey/tests/sandbox/Plugins/EnumeratePlugin.cs index 9f8fda54..2671944a 100644 --- a/Yubico.YubiKey/tests/sandbox/Plugins/EnumeratePlugin.cs +++ b/Yubico.YubiKey/tests/sandbox/Plugins/EnumeratePlugin.cs @@ -75,12 +75,12 @@ private bool OutputDevices(Transport transport) IList keys = IntegrationTestDeviceEnumeration.GetTestDevices(transport); if (keys.Count == 0) { - Output.WriteLine($"No keys found of type [{ transport }]"); + Output.WriteLine($"No keys found of type [{transport}]"); return false; } for (int i = 0; i < keys.Count; ++i) { - Output.WriteLine($"{ Eol }YubiKey # { i + 1 }{ Eol + keys[i] }"); + Output.WriteLine($"{Eol}YubiKey # {i + 1}{Eol + keys[i]}"); Output.WriteLine(new string('-', ConsoleWidth - 1)); } Output.WriteLine(new string('=', ConsoleWidth - 1)); diff --git a/Yubico.YubiKey/tests/sandbox/Plugins/EventManagerPlugin.cs b/Yubico.YubiKey/tests/sandbox/Plugins/EventManagerPlugin.cs index c296d987..00c97bf0 100644 --- a/Yubico.YubiKey/tests/sandbox/Plugins/EventManagerPlugin.cs +++ b/Yubico.YubiKey/tests/sandbox/Plugins/EventManagerPlugin.cs @@ -39,7 +39,7 @@ public EventManagerPlugin(IOutput output) : base(output) { } public override bool Execute() { - using var log = new LoggerConfiguration() + using Logger? log = new LoggerConfiguration() .Enrich.With(new ThreadIdEnricher()) .WriteTo.Console( outputTemplate: "[{Level}] ({ThreadId}) {Message}{NewLine}{Exception}") diff --git a/Yubico.YubiKey/tests/sandbox/Plugins/GregPlugin.cs b/Yubico.YubiKey/tests/sandbox/Plugins/GregPlugin.cs index 28c9c6d7..999ac5de 100644 --- a/Yubico.YubiKey/tests/sandbox/Plugins/GregPlugin.cs +++ b/Yubico.YubiKey/tests/sandbox/Plugins/GregPlugin.cs @@ -34,7 +34,7 @@ public GregPlugin(IOutput output) : base(output) { } public override bool Execute() { - using var log = new LoggerConfiguration() + using Serilog.Core.Logger? log = new LoggerConfiguration() .Enrich.With(new ThreadIdEnricher()) .WriteTo.Console( outputTemplate: "[{Level}] ({ThreadId}) {Message}{NewLine}{Exception}") @@ -45,7 +45,7 @@ public override bool Execute() .AddSerilog(log) .AddFilter(level => level >= LogLevel.Information)); - var yubiKey = YubiKeyDevice.FindAll().First(); + IYubiKeyDevice? yubiKey = YubiKeyDevice.FindAll().First(); Console.WriteLine($"YubiKey Version: {yubiKey.FirmwareVersion}"); @@ -60,7 +60,7 @@ public override bool Execute() var command = new GetAes128SessionKeysCommand(label, password, hostChallenge, hsmDeviceChallenge); Console.WriteLine("Calling calculate..."); - var response = hsmAuth.Connection.SendCommand(command); + GetAes128SessionKeysResponse? response = hsmAuth.Connection.SendCommand(command); Console.WriteLine($"Calculate returned with {response.Status}"); } diff --git a/Yubico.YubiKey/tests/sandbox/Plugins/HidCodeTablePlugin.cs b/Yubico.YubiKey/tests/sandbox/Plugins/HidCodeTablePlugin.cs index 731ceecd..f92a2c37 100644 --- a/Yubico.YubiKey/tests/sandbox/Plugins/HidCodeTablePlugin.cs +++ b/Yubico.YubiKey/tests/sandbox/Plugins/HidCodeTablePlugin.cs @@ -69,11 +69,11 @@ public HidCodeTablePlugin(IOutput output) : base(output) Type = typeof(IEnumerable), Description = "A list (or single one of) keyboard IDs to print lookup tables for. " + - $"If you're adding a new layout, you'll need to edit { Path.GetFileName(GetSourceFile()) }. " + + $"If you're adding a new layout, you'll need to edit {Path.GetFileName(GetSourceFile())}. " + "If nothing is specified, all current supported layouts are printed." }; Parameters["command"].Description = - "Possible values are 'info' and 'print'. The 'info' command prints a list of LCID IDs and bit values. "+ + "Possible values are 'info' and 'print'. The 'info' command prints a list of LCID IDs and bit values. " + "The 'print' command prints the lookup tables (generated C# code)."; Converters[typeof(IEnumerable)] = (s) => ParseStringCollection(s); @@ -113,9 +113,9 @@ public override bool Execute() } Output.WriteLine("LCID IDs and Bit Values:"); - foreach((string ID, string LCID) in _keyboardLayouts.Select(kvp => (kvp.Key, kvp.Value.LCID))) + foreach ((string ID, string LCID) in _keyboardLayouts.Select(kvp => (kvp.Key, kvp.Value.LCID))) { - Output.WriteLine($"[{ ID }] => [{ LCID }]"); + Output.WriteLine($"[{ID}] => [{LCID}]"); } return true; @@ -134,10 +134,10 @@ public bool PrintTables() "using System.Collections.Generic;" + Eol + "using Yubico.Core.Devices.Hid;" + Eol + Eol + "namespace Yubico.YubiKey.Otp" + Eol + "{" + Eol + - $" // Keyboard Mapping for { name }." + Eol + + $" // Keyboard Mapping for {name}." + Eol + " public sealed partial class HidCodeTranslator" + Eol + " {" + Eol + - $" private static HidCodeTranslator Get{ (name == "ModHex" ? name : name.ToUpper()) }()" + Eol + + $" private static HidCodeTranslator Get{(name == "ModHex" ? name : name.ToUpper())}()" + Eol + " {" + Eol + " var byChar = new Dictionary"); PrintItems("['{0}'] = 0x{1},"); @@ -147,7 +147,7 @@ public bool PrintTables() PrintItems("[0x{1}] = '{0}',"); Output.WriteLine(Eol + lineStart + - $"return new HidCodeTranslator(byChar, byCode, KeyboardLayout.{ name });" + Eol + + $"return new HidCodeTranslator(byChar, byCode, KeyboardLayout.{name});" + Eol + " }" + Eol + " }" + Eol + "}" + Eol); @@ -172,7 +172,7 @@ void PrintItems(string template) prefix = itemLineStart; linePosition = item.Length + prefix.Length; } - Output.Write($"{ prefix }{ item }"); + Output.Write($"{prefix}{item}"); } } Output.WriteLine(Eol + lineStart + "};"); @@ -240,7 +240,7 @@ private static (string ch, bool shifted)[] GetChar(IntPtr layout, uint scanCode) } if (result != 1) { - System.Diagnostics.Debug.WriteLine($"Got [{ result }] from [0x{ scanCode.ToString("x2") }] Shift [{ shifted }]"); + System.Diagnostics.Debug.WriteLine($"Got [{result}] from [0x{scanCode.ToString("x2")}] Shift [{shifted}]"); } } return results.ToArray(); diff --git a/Yubico.YubiKey/tests/sandbox/Plugins/JamiePlugin.cs b/Yubico.YubiKey/tests/sandbox/Plugins/JamiePlugin.cs index ec81c46c..769d3114 100644 --- a/Yubico.YubiKey/tests/sandbox/Plugins/JamiePlugin.cs +++ b/Yubico.YubiKey/tests/sandbox/Plugins/JamiePlugin.cs @@ -16,10 +16,10 @@ using System.Collections.Generic; using System.Linq; using System.Security.Cryptography; +using Yubico.Core.Devices.Hid; using Yubico.YubiKey.Cryptography; using Yubico.YubiKey.Otp; using Yubico.YubiKey.Otp.Commands; -using Yubico.Core.Devices.Hid; namespace Yubico.YubiKey.TestApp.Plugins { @@ -41,7 +41,7 @@ public override bool Execute() "setstaticpassword" => SetStaticPassword(), "swapslots" => SwapSlots(), "printrandomstring" => PrintRandomBytes(), - _ => throw new ArgumentException($"Invalid command [{ Command }] specified") + _ => throw new ArgumentException($"Invalid command [{Command}] specified") }; } @@ -70,7 +70,7 @@ private bool SwapSlots() var statusCmd = new ReadStatusCommand(); ReadStatusResponse? statusx = connection.SendCommand(statusCmd); OtpStatus? data = statusx.GetData(); - Output.WriteLine($"Data is { data }"); + Output.WriteLine($"Data is {data}"); var cmd = new SwapSlotsCommand(); ReadStatusResponse response = connection.SendCommand(cmd); @@ -103,7 +103,7 @@ private bool SetStaticPassword() catch (Exception ex) { throw new PluginFailureException( - $"Error [{ ex.Message }] executing command [{ Command }]", + $"Error [{ex.Message}] executing command [{Command}]", ex); } } diff --git a/Yubico.YubiKey/tests/sandbox/Plugins/OathPlugin.cs b/Yubico.YubiKey/tests/sandbox/Plugins/OathPlugin.cs index 9db84979..036d82fa 100644 --- a/Yubico.YubiKey/tests/sandbox/Plugins/OathPlugin.cs +++ b/Yubico.YubiKey/tests/sandbox/Plugins/OathPlugin.cs @@ -46,7 +46,7 @@ public override bool Execute() IEnumerable keys = YubiKeyDevice.FindAll(); IYubiKeyDevice? yubiKey = keys.First(); - + using var oathSession = new OathSession(yubiKey); // Copy URI string from Authenticator Test console and pass here. diff --git a/Yubico.YubiKey/tests/sandbox/Plugins/Otp/Calculate.cs b/Yubico.YubiKey/tests/sandbox/Plugins/Otp/Calculate.cs index 200243e2..f39fa862 100644 --- a/Yubico.YubiKey/tests/sandbox/Plugins/Otp/Calculate.cs +++ b/Yubico.YubiKey/tests/sandbox/Plugins/Otp/Calculate.cs @@ -43,7 +43,7 @@ public override bool Execute() if (!(_slot == Slot.ShortPress ? otp.IsShortPressConfigured : otp.IsLongPressConfigured)) { Output.WriteLine( - $"Slot[{ _slot }] is not programmed and can't be used for a challenge-response transaction.", + $"Slot[{_slot}] is not programmed and can't be used for a challenge-response transaction.", OutputLevel.Error); Output.WriteLine("Aborted.", OutputLevel.Error); return false; @@ -71,7 +71,7 @@ public override bool Execute() catch (Exception ex) { Output.WriteLine( - $"Error attempting to calculate challenge response: { ex.Message }.", + $"Error attempting to calculate challenge response: {ex.Message}.", OutputLevel.Error); return false; } @@ -80,8 +80,8 @@ public override bool Execute() { Output.WriteLine( _digits.HasValue - ? $"OTP Code is [{ result }]" - : $"Response is [{ result }]"); + ? $"OTP Code is [{result}]" + : $"Response is [{result}]"); } else { @@ -138,7 +138,7 @@ public override void HandleParameters() if (exceptions.Count > 1) { - throw new AggregateException($"{ exceptions.Count } errors encountered.", + throw new AggregateException($"{exceptions.Count} errors encountered.", exceptions); } else if (exceptions.Count == 1) diff --git a/Yubico.YubiKey/tests/sandbox/Plugins/Otp/ChallengeResponse.cs b/Yubico.YubiKey/tests/sandbox/Plugins/Otp/ChallengeResponse.cs index 7ec57249..3356c626 100644 --- a/Yubico.YubiKey/tests/sandbox/Plugins/Otp/ChallengeResponse.cs +++ b/Yubico.YubiKey/tests/sandbox/Plugins/Otp/ChallengeResponse.cs @@ -117,7 +117,7 @@ public override void HandleParameters() throw exceptions.Count == 1 ? exceptions[0] : new AggregateException( - $"{ exceptions.Count } errors encountered.", + $"{exceptions.Count} errors encountered.", exceptions); } } @@ -156,7 +156,7 @@ public override bool Execute() private void OutputResult() { - Output.WriteLine($"Challenge-response ({ (_yubiOtp ? "Yubico OTP" : "HMAC-SHA1") }) configured."); + Output.WriteLine($"Challenge-response ({(_yubiOtp ? "Yubico OTP" : "HMAC-SHA1")}) configured."); if (_generate || _generateTotp || Output.OutputLevel > OutputLevel.Normal) { @@ -175,7 +175,7 @@ private void OutputResult() ? new ModHex() : new Base16(); encoding.Encode(_key, encodedKey); - Output.Write((_generate ? "Generated " : string.Empty) + $"Key ({ encoding.GetType() }): "); + Output.Write((_generate ? "Generated " : string.Empty) + $"Key ({encoding.GetType()}): "); Output.WriteSensitive(encodedKey, OutputLevel.Quiet); Output.WriteLine(string.Empty, OutputLevel.Quiet); } @@ -184,7 +184,7 @@ private void OutputResult() encodedKey.Clear(); } Output.WriteLine("Mode: " + (_yubiOtp ? "Yubico OTP" : "HMAC-SHA1"), OutputLevel.Verbose); - Output.WriteLine($"Button press: { (_button ? string.Empty : "Not ") } required"); + Output.WriteLine($"Button press: {(_button ? string.Empty : "Not ")} required"); } //// if outputlevel is none or error, then no output here. diff --git a/Yubico.YubiKey/tests/sandbox/Plugins/Otp/Delete.cs b/Yubico.YubiKey/tests/sandbox/Plugins/Otp/Delete.cs index 570b6c49..297be176 100644 --- a/Yubico.YubiKey/tests/sandbox/Plugins/Otp/Delete.cs +++ b/Yubico.YubiKey/tests/sandbox/Plugins/Otp/Delete.cs @@ -42,7 +42,7 @@ public override bool Execute() { using var otp = new OtpSession(_yubiKey!); - if (!Verify(otp, $"Type \"Yes\" to delete slot[{ _slot }] configuration.")) + if (!Verify(otp, $"Type \"Yes\" to delete slot[{_slot}] configuration.")) { Output.WriteLine("Aborted.", OutputLevel.Error); return false; @@ -52,12 +52,12 @@ public override bool Execute() otp.DeleteSlotConfiguration(_slot) .UseCurrentAccessCode((SlotAccessCode)_currentAccessCode) .Execute(); - Output.WriteLine($"Configuration in OTP slot [{ _slot }] deleted."); + Output.WriteLine($"Configuration in OTP slot [{_slot}] deleted."); } catch (Exception ex) { throw new PluginFailureException( - $"Error executing OtpSession.DeleteSlotConfiguration: { ex.Message }.", + $"Error executing OtpSession.DeleteSlotConfiguration: {ex.Message}.", ex); } diff --git a/Yubico.YubiKey/tests/sandbox/Plugins/Otp/Hotp.cs b/Yubico.YubiKey/tests/sandbox/Plugins/Otp/Hotp.cs index 328441f5..ff60ea0e 100644 --- a/Yubico.YubiKey/tests/sandbox/Plugins/Otp/Hotp.cs +++ b/Yubico.YubiKey/tests/sandbox/Plugins/Otp/Hotp.cs @@ -101,7 +101,7 @@ public override void HandleParameters() throw exceptions.Count == 1 ? exceptions[0] : new AggregateException( - $"{ exceptions.Count } errors encountered.", + $"{exceptions.Count} errors encountered.", exceptions); } } @@ -124,7 +124,7 @@ public override bool Execute() catch (Exception ex) { throw new PluginFailureException( - $"Error executing OtpSession.ConfigureHotp: { ex.Message }.", + $"Error executing OtpSession.ConfigureHotp: {ex.Message}.", ex); } @@ -158,8 +158,8 @@ private void OutputResult(ConfigureHotp op) Output.Write((_generate ? "Generated " : string.Empty) + "Key (base-32): "); Output.WriteSensitive(encoded, OutputLevel.Quiet); Output.WriteLine(string.Empty, OutputLevel.Quiet); - Output.WriteLine($"OTP Length: { _digits } digits", OutputLevel.Verbose); - Output.WriteLine($"Initial Moving Factor: { _imf }", OutputLevel.Verbose); + Output.WriteLine($"OTP Length: {_digits} digits", OutputLevel.Verbose); + Output.WriteLine($"Initial Moving Factor: {_imf}", OutputLevel.Verbose); } finally { diff --git a/Yubico.YubiKey/tests/sandbox/Plugins/Otp/Ndef.cs b/Yubico.YubiKey/tests/sandbox/Plugins/Otp/Ndef.cs index 9e70985d..73c576d5 100644 --- a/Yubico.YubiKey/tests/sandbox/Plugins/Otp/Ndef.cs +++ b/Yubico.YubiKey/tests/sandbox/Plugins/Otp/Ndef.cs @@ -55,7 +55,7 @@ public override void HandleParameters() exceptions.Add(new InvalidOperationException( "You cannot read and program an NDEF tag in the same operation.")); } - if(_slot != Slot.None) + if (_slot != Slot.None) { exceptions.Add(new InvalidOperationException( "Setting the slot is not relevant when reading an NDEF tag.")); @@ -80,7 +80,7 @@ public override void HandleParameters() { Output.WriteLine( _serialNumber.HasValue - ? $"Touch YubiKey with serial number { _serialNumber.Value } to NFC reader." + ? $"Touch YubiKey with serial number {_serialNumber.Value} to NFC reader." : "Touch YubiKey to NFC reader.", OutputLevel.Quiet); var timer = Stopwatch.StartNew(); @@ -111,7 +111,7 @@ public override void HandleParameters() throw exceptions.Count == 1 ? exceptions[0] : new AggregateException( - $"{ exceptions.Count } errors encountered.", + $"{exceptions.Count} errors encountered.", exceptions); } @@ -136,8 +136,8 @@ string raw() => string labeled() => reader.Type == NdefDataType.Uri - ? $"URI Read: { raw() }" - : $"Text Read: { raw() }"; + ? $"URI Read: {raw()}" + : $"Text Read: {raw()}"; string detailed() => reader.Type == NdefDataType.Uri @@ -194,7 +194,7 @@ string uriDetails(Uri uri) => $"Path: { uri.AbsolutePath }" }); string textDetails(string text, string lcid, NdefTextEncoding encoding) => - $"Text: { text + Eol }LCID: { lcid + Eol }Encoding: { encoding }"; + $"Text: {text + Eol}LCID: {lcid + Eol}Encoding: {encoding}"; } } } diff --git a/Yubico.YubiKey/tests/sandbox/Plugins/Otp/OtpPluginBase.cs b/Yubico.YubiKey/tests/sandbox/Plugins/Otp/OtpPluginBase.cs index db14f629..4dc5a668 100644 --- a/Yubico.YubiKey/tests/sandbox/Plugins/Otp/OtpPluginBase.cs +++ b/Yubico.YubiKey/tests/sandbox/Plugins/Otp/OtpPluginBase.cs @@ -95,9 +95,7 @@ public OtpPluginBase(IOutput output) : base(output) Name = "Keyboard", Shortcut = "kb", Description = "Keyboard layout to use for the static password. " + - $@"Choices are { - string.Join(',', Enum.GetNames(typeof(KeyboardLayout))) - } [default: ModHex]", + $@"Choices are {string.Join(',', Enum.GetNames(typeof(KeyboardLayout)))} [default: ModHex]", Type = typeof(KeyboardLayout) }), ParameterUse.CurrentAccessCode => new KeyValuePair( @@ -341,7 +339,7 @@ public OtpPluginBase(IOutput output) : base(output) Type = typeof(string) }), _ => throw new InvalidOperationException( - $"Invalid value [{ p }] in { GetType().Name }.ParametersUsed collection.") + $"Invalid value [{p}] in {GetType().Name}.ParametersUsed collection.") }) // For now, I'll assume that this parameter will be available to all OTP plugins. .Append(new KeyValuePair( @@ -361,7 +359,7 @@ public OtpPluginBase(IOutput output) : base(output) { throw new InvalidOperationException( "Error building parameters object. Likely problem is incompatible " - + $"parameters specified in class [{ GetType().Name }].", + + $"parameters specified in class [{GetType().Name}].", ex); } } @@ -409,13 +407,13 @@ public override void HandleParameters() _button = (bool?)GetParameter("button") ?? false; _text = (string?)GetParameter("text") ?? string.Empty; _uri = (Uri?)GetParameter("uri"); - _encoding = ((bool?)GetParameter("utf16") ?? false) ? NdefTextEncoding.Utf16 : NdefTextEncoding.Utf8; + _encoding = (bool?)GetParameter("utf16") ?? false ? NdefTextEncoding.Utf16 : NdefTextEncoding.Utf8; _read = (bool?)GetParameter("read") ?? false; _lcid = (string?)GetParameter("languageid") ?? string.Empty; _imf = (int?)GetParameter("initialmovingfactor") ?? 0; _text = (string?)GetParameter("text") ?? string.Empty; _uri = (Uri?)GetParameter("uri"); - _encoding = ((bool?)GetParameter("utf16") ?? false) ? NdefTextEncoding.Utf16 : NdefTextEncoding.Utf8; + _encoding = (bool?)GetParameter("utf16") ?? false ? NdefTextEncoding.Utf16 : NdefTextEncoding.Utf8; _read = (bool?)GetParameter("read") ?? false; _lcid = (string?)GetParameter("languageid") ?? string.Empty; @@ -455,11 +453,11 @@ internal static IYubiKeyDevice GetYubiKey(int? serialNumber, Transport transport if (keys.Skip(1).Any()) { string keystr = string.Join(", ", keys.Select(k => k.SerialNumber)); - subMessage = $" Keys found: [{ keystr }]."; + subMessage = $" Keys found: [{keystr}]."; } else { - subMessage = $" Key found: [{ keys.First().SerialNumber }]."; + subMessage = $" Key found: [{keys.First().SerialNumber}]."; } } string exText = string.Format(message, serialNumber, subMessage); @@ -494,7 +492,7 @@ protected bool Verify(OtpSession otp, string? message = null) // user doesn't want to be prompted. if (Output.OutputLevel >= OutputLevel.Normal) { - message ??= $"Slot[{ _slot }] is already programmed. { Eol }" + + message ??= $"Slot[{_slot}] is already programmed. {Eol}" + "Type \"Yes\" and press [Enter] to overwrite"; // This is an exception to the "Always use Output" rule. // Outputing a prompt to type "yes" to a file would be worse @@ -509,7 +507,7 @@ protected bool Verify(OtpSession otp, string? message = null) else { Output.WriteLine( - $"Slot[{ _slot }] is already programmed." + Eol + + $"Slot[{_slot}] is already programmed." + Eol + "Either select the [-force] option, or don't select [-quiet] to be prompted.", OutputLevel.Error); } diff --git a/Yubico.YubiKey/tests/sandbox/Plugins/Otp/Static.cs b/Yubico.YubiKey/tests/sandbox/Plugins/Otp/Static.cs index 60309f67..ab6e909b 100644 --- a/Yubico.YubiKey/tests/sandbox/Plugins/Otp/Static.cs +++ b/Yubico.YubiKey/tests/sandbox/Plugins/Otp/Static.cs @@ -85,7 +85,7 @@ public override void HandleParameters() if (exceptions.Count > 1) { - throw new AggregateException($"{ exceptions.Count } errors encountered.", + throw new AggregateException($"{exceptions.Count} errors encountered.", exceptions); } else if (exceptions.Count == 1) @@ -180,7 +180,7 @@ public override bool Execute() catch (Exception ex) { throw new PluginFailureException( - $"Error executing OtpSession.SetStaticPassword: { ex.Message }.", + $"Error executing OtpSession.SetStaticPassword: {ex.Message}.", ex); } diff --git a/Yubico.YubiKey/tests/sandbox/Plugins/Otp/Swap.cs b/Yubico.YubiKey/tests/sandbox/Plugins/Otp/Swap.cs index 81422668..73dc7e23 100644 --- a/Yubico.YubiKey/tests/sandbox/Plugins/Otp/Swap.cs +++ b/Yubico.YubiKey/tests/sandbox/Plugins/Otp/Swap.cs @@ -60,7 +60,7 @@ public override bool Execute() } catch (Exception ex) { - throw new PluginFailureException($"Error executing OtpSession.SwapSlots: { ex.Message }.", ex); + throw new PluginFailureException($"Error executing OtpSession.SwapSlots: {ex.Message}.", ex); } return true; diff --git a/Yubico.YubiKey/tests/sandbox/Plugins/Otp/UpdateSlot.cs b/Yubico.YubiKey/tests/sandbox/Plugins/Otp/UpdateSlot.cs index 6772517c..a0d5f79a 100644 --- a/Yubico.YubiKey/tests/sandbox/Plugins/Otp/UpdateSlot.cs +++ b/Yubico.YubiKey/tests/sandbox/Plugins/Otp/UpdateSlot.cs @@ -207,7 +207,7 @@ public override bool Execute() : otp.IsLongPressConfigured; if (!ready) { - Output.WriteLine($"Slot[{ _slot }] is not programmed and can't be updated."); + Output.WriteLine($"Slot[{_slot}] is not programmed and can't be updated."); Output.WriteLine("Aborted."); return false; } @@ -242,23 +242,23 @@ public override bool Execute() private bool ConfirmConfig() { Output.WriteLine(_force - ? $"Updating Configuration for Slot [{ _slot }]:" - : $"Proposed Configuration for slot [{ _slot }]:"); + ? $"Updating Configuration for Slot [{_slot}]:" + : $"Proposed Configuration for slot [{_slot}]:"); Output.WriteLine(new string('-', 80)); - Output.Write($"AppendDelayToFixed: | { Val(_appendDelayToFixed) } | AppendDelayToOtp: "); - Output.WriteLine($"{ Val(_appendDelayToOtp) } | Dormant: { Val(_dormant) }"); + Output.Write($"AppendDelayToFixed: | {Val(_appendDelayToFixed)} | AppendDelayToOtp: "); + Output.WriteLine($"{Val(_appendDelayToOtp)} | Dormant: {Val(_dormant)}"); Output.WriteLine(new string('-', 80)); - Output.Write($"SerialVisibleToApi: | { Val(_serialApi) } | UseNumericKeypad: "); - Output.WriteLine($"{ Val(_numericKeypad) } | 10msPacing: { Val(_use10msPacing) }"); + Output.Write($"SerialVisibleToApi: | {Val(_serialApi)} | UseNumericKeypad: "); + Output.WriteLine($"{Val(_numericKeypad)} | 10msPacing: {Val(_use10msPacing)}"); Output.WriteLine(new string('-', 80)); - Output.Write($"SerialVisibleToButton: | { Val(_serialButton) } | AppendTabToFixed: "); - Output.WriteLine($"{ Val(_appendTabToFixed) } | 20msPacing: { Val(_use20msPacing) }"); + Output.Write($"SerialVisibleToButton: | {Val(_serialButton)} | AppendTabToFixed: "); + Output.WriteLine($"{Val(_appendTabToFixed)} | 20msPacing: {Val(_use20msPacing)}"); Output.WriteLine(new string('-', 80)); - Output.Write($"SerialVisibleToUsb: | { Val(_serialUsb) } | AppendTabToOtp: "); - Output.WriteLine($"{ Val(_appendTabToOtp) } | NoEnter: { Val(_noEnter) }"); + Output.Write($"SerialVisibleToUsb: | {Val(_serialUsb)} | AppendTabToOtp: "); + Output.WriteLine($"{Val(_appendTabToOtp)} | NoEnter: {Val(_noEnter)}"); Output.WriteLine(new string('-', 80)); - Output.Write($"SendTabFirst: | { Val(_sendTabFirst) } | FastTrigger: "); - Output.WriteLine($"{ Val(_fastTrigger) } | InvertLed: { Val(_invertLed) }"); + Output.Write($"SendTabFirst: | {Val(_sendTabFirst)} | FastTrigger: "); + Output.WriteLine($"{Val(_fastTrigger)} | InvertLed: {Val(_invertLed)}"); Output.WriteLine(new string('-', 80) + Environment.NewLine); if (_force) diff --git a/Yubico.YubiKey/tests/sandbox/Plugins/Otp/ValidateHotp.cs b/Yubico.YubiKey/tests/sandbox/Plugins/Otp/ValidateHotp.cs index 3cc29d2a..4319fbc1 100644 --- a/Yubico.YubiKey/tests/sandbox/Plugins/Otp/ValidateHotp.cs +++ b/Yubico.YubiKey/tests/sandbox/Plugins/Otp/ValidateHotp.cs @@ -97,21 +97,21 @@ public override void HandleParameters() catch (Exception ex) { exceptions.Add(new InvalidOperationException( - $"Error decoding passcode digits: { ex.Message }", + $"Error decoding passcode digits: {ex.Message}", ex)); } if (_password.Length != _digits) { exceptions.Add(new InvalidOperationException( - $"Passcode supplied ({ _password }) is not the correct length. " + - $"Expected { _digits } digits.")); + $"Passcode supplied ({_password}) is not the correct length. " + + $"Expected {_digits} digits.")); } } if (_imf < 0 || _imf > 0xffff0) { throw new InvalidOperationException( - $"Invalid IMF ({ _imf }). IMF must be between 0 and 1048560 (0xffff0)."); + $"Invalid IMF ({_imf}). IMF must be between 0 and 1048560 (0xffff0)."); } else { @@ -127,7 +127,7 @@ public override void HandleParameters() throw exceptions.Count == 1 ? exceptions[0] : new AggregateException( - $"{ exceptions.Count } errors encountered.", + $"{exceptions.Count} errors encountered.", exceptions); } diff --git a/Yubico.YubiKey/tests/sandbox/Plugins/Otp/YubiOtp.cs b/Yubico.YubiKey/tests/sandbox/Plugins/Otp/YubiOtp.cs index 6d433bac..c7da45d6 100644 --- a/Yubico.YubiKey/tests/sandbox/Plugins/Otp/YubiOtp.cs +++ b/Yubico.YubiKey/tests/sandbox/Plugins/Otp/YubiOtp.cs @@ -150,7 +150,7 @@ public override void HandleParameters() throw exceptions.Count == 1 ? exceptions[0] : new AggregateException( - $"{ exceptions.Count } errors encountered.", + $"{exceptions.Count} errors encountered.", exceptions); } @@ -198,7 +198,7 @@ public override bool Execute() catch (Exception ex) { throw new PluginFailureException( - $"Error executing OtpSession.ConfigureYubicoOtp: { ex.Message }.", + $"Error executing OtpSession.ConfigureYubicoOtp: {ex.Message}.", ex); } @@ -247,14 +247,14 @@ bool PropOut(string name, Span value, bool generated, bool leadWithSeparat || (Output.OutputLevel == OutputLevel.Normal && generated)) { Output.Write( - $"{ sep }{ (generated ? "Generated " : string.Empty) }{ name }: ", + $"{sep}{(generated ? "Generated " : string.Empty)}{name}: ", OutputLevel.Quiet); Output.WriteSensitive(value, OutputLevel.Quiet); return true; } else if (generated) { - Output.Write($"{ sep }{ name.Replace(" ", null) }[", OutputLevel.Quiet); + Output.Write($"{sep}{name.Replace(" ", null)}[", OutputLevel.Quiet); Output.WriteSensitive(value, OutputLevel.Quiet); Output.Write("]", OutputLevel.Quiet); return true; @@ -304,7 +304,7 @@ private Uri UploadToYubiCloud() catch (Exception ex) { throw new InvalidOperationException( - $"Sending credential to YubiCloud failed with error [{ ex.Message }]", + $"Sending credential to YubiCloud failed with error [{ex.Message}]", ex); } @@ -325,11 +325,11 @@ private Uri UploadToYubiCloud() if (errors.Length == 1) { throw new InvalidOperationException( - $"Upload to Yubico OTP server failed with BAD_REQUEST ({ GetYubiOtpErrors(errors).First() })."); + $"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 })")); + $"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); diff --git a/Yubico.YubiKey/tests/sandbox/Plugins/PluginBase.cs b/Yubico.YubiKey/tests/sandbox/Plugins/PluginBase.cs index 7272e016..f042016c 100644 --- a/Yubico.YubiKey/tests/sandbox/Plugins/PluginBase.cs +++ b/Yubico.YubiKey/tests/sandbox/Plugins/PluginBase.cs @@ -96,7 +96,7 @@ public PluginBase(IOutput output) [typeof(Base32Bytes)] = (s) => Base32Bytes.Encode(s), [typeof(Base16Bytes)] = (s) => Base16Bytes.Encode(s), [typeof(Uri)] = (s) => new Uri(s), - }; + }; /// /// The method that actually performs the main task the plugin is diff --git a/Yubico.YubiKey/tests/sandbox/Plugins/Scp03Plugin.cs b/Yubico.YubiKey/tests/sandbox/Plugins/Scp03Plugin.cs index 6fa0411e..96811f9f 100644 --- a/Yubico.YubiKey/tests/sandbox/Plugins/Scp03Plugin.cs +++ b/Yubico.YubiKey/tests/sandbox/Plugins/Scp03Plugin.cs @@ -37,7 +37,7 @@ public override bool Execute() return Command.ToLower() switch { "e2e" => BasicE2ETest(), - _ => throw new ArgumentException($"Invalid command [{ Command }] specified") + _ => throw new ArgumentException($"Invalid command [{Command}] specified") }; } diff --git a/Yubico.YubiKey/tests/sandbox/Plugins/SmartCardDeviceListenerPlugin.cs b/Yubico.YubiKey/tests/sandbox/Plugins/SmartCardDeviceListenerPlugin.cs index f8fc7c40..51f0d3c6 100644 --- a/Yubico.YubiKey/tests/sandbox/Plugins/SmartCardDeviceListenerPlugin.cs +++ b/Yubico.YubiKey/tests/sandbox/Plugins/SmartCardDeviceListenerPlugin.cs @@ -46,10 +46,10 @@ public override bool Execute() listener.Arrived += (sender, args) => { - using var connection = args.Device.Connect(); + using ISmartCardConnection? connection = args.Device.Connect(); Console.WriteLine("Device arrived!"); - using var transaction = connection.BeginTransaction(out bool cardWasReset); + using IDisposable? transaction = connection.BeginTransaction(out bool cardWasReset); _ = connection.Transmit(new SelectApplicationCommand(YubiKeyApplication.Management).CreateCommandApdu()); }; listener.Removed += (sender, args) => Console.WriteLine("Device removed!"); diff --git a/Yubico.YubiKey/tests/sandbox/Plugins/U2fPlugin.cs b/Yubico.YubiKey/tests/sandbox/Plugins/U2fPlugin.cs index 57876c31..5fe7248d 100644 --- a/Yubico.YubiKey/tests/sandbox/Plugins/U2fPlugin.cs +++ b/Yubico.YubiKey/tests/sandbox/Plugins/U2fPlugin.cs @@ -105,7 +105,7 @@ public override void HandleParameters() _runRegisterTest = true; break; default: - throw new ArgumentException($"[{ Command }] is not a valid command for this plugin"); + throw new ArgumentException($"[{Command}] is not a valid command for this plugin"); } } diff --git a/Yubico.YubiKey/tests/sandbox/Plugins/YubiKeyFeaturePlugin.cs b/Yubico.YubiKey/tests/sandbox/Plugins/YubiKeyFeaturePlugin.cs index 90f6c076..2ef226c3 100644 --- a/Yubico.YubiKey/tests/sandbox/Plugins/YubiKeyFeaturePlugin.cs +++ b/Yubico.YubiKey/tests/sandbox/Plugins/YubiKeyFeaturePlugin.cs @@ -65,12 +65,12 @@ private void OutputResult(YubiKeyFeature feature) if (result) { - Output.WriteLine($"The feature [{ feature }] is available on this YubiKey"); + Output.WriteLine($"The feature [{feature}] is available on this YubiKey"); Output.WriteLine(); } else { - Output.WriteLine($"The feature [{ feature }] is not available on this YubiKey"); + Output.WriteLine($"The feature [{feature}] is not available on this YubiKey"); Output.WriteLine(); } } diff --git a/Yubico.YubiKey/tests/sandbox/Program.cs b/Yubico.YubiKey/tests/sandbox/Program.cs index 8cd8dd44..2081cd58 100644 --- a/Yubico.YubiKey/tests/sandbox/Program.cs +++ b/Yubico.YubiKey/tests/sandbox/Program.cs @@ -18,8 +18,8 @@ using System.IO; using System.Linq; using System.Text; -using Yubico.YubiKey.TestApp.Plugins.Otp; using Yubico.YubiKey.TestApp.Plugins; +using Yubico.YubiKey.TestApp.Plugins.Otp; using Yubico.YubiKey.TestUtilities; namespace Yubico.YubiKey.TestApp @@ -80,7 +80,7 @@ private int Execute(string[] args) } catch (Exception ex) { - WriteLine($"Error parsing command line [{ ex.Message }].", OutputLevel.Error); + WriteLine($"Error parsing command line [{ex.Message}].", OutputLevel.Error); Usage(true); return -1; } @@ -91,12 +91,12 @@ private int Execute(string[] args) try { ParseConfigFile(); - WriteLine($"Config file [{ _configFile }] parsed."); + WriteLine($"Config file [{_configFile}] parsed."); } catch (Exception ex) { - WriteLine($"Error: { ex.Message }.", OutputLevel.Error); - WriteLine($"File: { _configFile }", OutputLevel.Error); + WriteLine($"Error: {ex.Message}.", OutputLevel.Error); + WriteLine($"File: {_configFile}", OutputLevel.Error); return -1; } } @@ -132,7 +132,7 @@ private int Execute(string[] args) } catch (Exception ex) { - WriteLine($"Error processing parameters [{ ex.Message }].", OutputLevel.Error); + WriteLine($"Error processing parameters [{ex.Message}].", OutputLevel.Error); return -1; } @@ -140,17 +140,17 @@ private int Execute(string[] args) // Nothing to it but to do it. //try //{ - WriteLine("Calling plugins Execute() method."); - bool result = _plugin?.Execute() ?? false; - WriteLine($"Plugin's Execute() method returned [{ result }]", OutputLevel.Verbose); - returnValue = result ? 0 : -1; + WriteLine("Calling plugins Execute() method."); + bool result = _plugin?.Execute() ?? false; + WriteLine($"Plugin's Execute() method returned [{result}]", OutputLevel.Verbose); + returnValue = result ? 0 : -1; //} //catch (Exception ex) //{ // WriteLine($"Exception in plugin [{ _plugin.Name }]: { ex.Message }.", OutputLevel.Error); // returnValue = -1; //} - Write($"Returning [{ returnValue }] to command shell.", OutputLevel.Verbose); + Write($"Returning [{returnValue}] to command shell.", OutputLevel.Verbose); return returnValue; } @@ -190,7 +190,7 @@ private void Usage(bool asError = false) + "If you do not supply a full path, the current working " + "directory is the starting point."), }; - if (_plugin is null || ((_outputLevel ?? OutputLevel.Normal) == OutputLevel.Verbose)) + if (_plugin is null || (_outputLevel ?? OutputLevel.Normal) == OutputLevel.Verbose) { paramUsage.Add(("Plug-ins", string.Empty)); } @@ -204,7 +204,7 @@ private void Usage(bool asError = false) foreach (PluginBase plugin in plugIns) { - if (_plugin is null && ((_outputLevel ?? OutputLevel.Normal) != OutputLevel.Verbose)) + if (_plugin is null && (_outputLevel ?? OutputLevel.Normal) != OutputLevel.Verbose) { // If there's no plug-in selected, show all of them, but only // descriptions so that we don't have pages of parameters. @@ -214,7 +214,7 @@ private void Usage(bool asError = false) { // If there is a plug-in selected, show all of its parameters // and their descriptions, but no description for the plug-in. - paramUsage.Add(($"{ plugin.Name } Parameters", string.Empty)); + paramUsage.Add(($"{plugin.Name} Parameters", string.Empty)); if (plugin.Parameters.Values.Any()) { foreach (Parameter parameter in plugin.Parameters.Values) @@ -255,7 +255,7 @@ private void Usage(bool asError = false) else { int spaces = maxFlagWidth - id.Length - 3; - _ = sb.Append($" { id }{ new string(' ', spaces)}"); + _ = sb.Append($" {id}{new string(' ', spaces)}"); WriteDescription(desc, maxFlagWidth); } } @@ -306,7 +306,7 @@ void WriteDescription(string description, int indent = 0) // will collect parameters from here and just store them. private void ParseCommandline(string[] args) { - WriteLine($"Parsing command line parameters [{ string.Join(", ", args) }].", OutputLevel.Verbose); + WriteLine($"Parsing command line parameters [{string.Join(", ", args)}].", OutputLevel.Verbose); for (int i = 0; i < args.Length; ++i) { string arg = args[i]; @@ -315,7 +315,7 @@ private void ParseCommandline(string[] args) // of it. if (arg[0] != '-' && arg[0] != '/') { - throw new ArgumentException($"[{ arg[0] }] was unexpected."); + throw new ArgumentException($"[{arg[0]}] was unexpected."); } // If the argument has a colon, then it can be assumed that the @@ -347,7 +347,7 @@ private void ParseCommandline(string[] args) // It will just be easier if this isn't case sensitive. name = name.ToLower(); - WriteLine($"Parsed parameter name[{ name }], value[{ value }]", OutputLevel.Verbose); + WriteLine($"Parsed parameter name[{name}], value[{value}]", OutputLevel.Verbose); // Since we're handling parameters from two different places, // we'll use a common method. @@ -361,7 +361,7 @@ private void ParseCommandline(string[] args) // it's used to parse the config file. private void HandleParameter(string key, string value) { - Write($"Processing [{ key }] with value [{ value }]...", OutputLevel.Verbose); + Write($"Processing [{key}] with value [{value}]...", OutputLevel.Verbose); bool isSet = true; switch (key) @@ -373,8 +373,8 @@ private void HandleParameter(string key, string value) } else { - Write($"Not setting [{ value }] as plugin. ", OutputLevel.Verbose); - WriteLine($"Plugin is already [{ _plugin.Name }].", OutputLevel.Verbose); + Write($"Not setting [{value}] as plugin. ", OutputLevel.Verbose); + WriteLine($"Plugin is already [{_plugin.Name}].", OutputLevel.Verbose); isSet = false; } @@ -424,7 +424,7 @@ private void HandleParameter(string key, string value) else { throw new ArgumentException( - $"Can't set [{ key }]. OutputLevel is already [{ _outputLevel.Value }]"); + $"Can't set [{key}]. OutputLevel is already [{_outputLevel.Value}]"); } break; @@ -449,9 +449,9 @@ private void HandleParameter(string key, string value) } else { - Write($"Not setting [{ key }] as [{ value }]. ", OutputLevel.Verbose); + Write($"Not setting [{key}] as [{value}]. ", OutputLevel.Verbose); WriteLine( - $"[{ key }] was already set, probably in your config file.", + $"[{key}] was already set, probably in your config file.", OutputLevel.Verbose); isSet = false; } @@ -470,7 +470,7 @@ private void ParseConfigFile() { if (!File.Exists(_configFile)) { - throw new FileNotFoundException($"Specified config file [{ _configFile }] doesn't exist."); + throw new FileNotFoundException($"Specified config file [{_configFile}] doesn't exist."); } var configMap = new ExeConfigurationFileMap @@ -495,7 +495,7 @@ private void SetPlugin(string plugin) { if (!_plugIns.TryGetValue(plugin, out Func? getter)) { - throw new InvalidOperationException($"Plugin [{ plugin }] not found."); + throw new InvalidOperationException($"Plugin [{plugin}] not found."); } _plugin = getter(this); @@ -522,7 +522,7 @@ private void ProcessParameters() { if (!parameters.TryGetValue(kvp.Key, out Parameter? parameter)) { - throw new ArgumentException($"Unexpected parameter [{ kvp.Key }] for plugin [{ plugin.Name }]"); + throw new ArgumentException($"Unexpected parameter [{kvp.Key}] for plugin [{plugin.Name}]"); } if (!plugin.Converters.TryGetValue(parameter.Type, out Func? converter)) @@ -542,7 +542,7 @@ private void ProcessParameters() catch (Exception ex) { throw new InvalidOperationException( - $"Error: { ex.Message }, Parameter: { parameter.Name }, Value: { kvp.Value }, Type: { parameter.Type }", + $"Error: {ex.Message}, Parameter: {parameter.Name}, Value: {kvp.Value}, Type: {parameter.Type}", ex); } diff --git a/Yubico.YubiKey/tests/unit/Yubico.YubiKey.UnitTests.csproj b/Yubico.YubiKey/tests/unit/Yubico.YubiKey.UnitTests.csproj index cb2348ce..362b27bb 100644 --- a/Yubico.YubiKey/tests/unit/Yubico.YubiKey.UnitTests.csproj +++ b/Yubico.YubiKey/tests/unit/Yubico.YubiKey.UnitTests.csproj @@ -33,9 +33,9 @@ limitations under the License. --> - - - + + + diff --git a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/ConnectionManagerTests.cs b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/ConnectionManagerTests.cs index 53ad4eb3..b8e22670 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/ConnectionManagerTests.cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/ConnectionManagerTests.cs @@ -26,10 +26,10 @@ namespace Yubico.YubiKey internal class TestSmartCardDevice : ISmartCardDevice { public readonly static ISmartCardDevice AnyInstance = new TestSmartCardDevice() - { Kind = SmartCardConnectionKind.Any }; + { Kind = SmartCardConnectionKind.Any }; public readonly static ISmartCardDevice NfcInstance = new TestSmartCardDevice() - { Kind = SmartCardConnectionKind.Nfc }; + { Kind = SmartCardConnectionKind.Nfc }; public DateTime LastAccessed { get; } = DateTime.Now; public string Path { get; } = string.Empty; diff --git a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Cryptography/AesCmacLongKeyTests.cs b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Cryptography/AesCmacLongKeyTests.cs index 10a9cb42..2942184a 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Cryptography/AesCmacLongKeyTests.cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Cryptography/AesCmacLongKeyTests.cs @@ -14,8 +14,8 @@ using System; using Xunit; -using Yubico.PlatformInterop; using Yubico.Core.Cryptography; +using Yubico.PlatformInterop; namespace Yubico.YubiKey.Cryptography { diff --git a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Cryptography/AesCmacTests.cs b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Cryptography/AesCmacTests.cs index 17ce5014..4e0cdfe4 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Cryptography/AesCmacTests.cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Cryptography/AesCmacTests.cs @@ -14,9 +14,9 @@ using System; using Xunit; -using Yubico.PlatformInterop; using Yubico.Core.Buffers; using Yubico.Core.Cryptography; +using Yubico.PlatformInterop; namespace Yubico.YubiKey.Cryptography { diff --git a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Cryptography/EcdsaVerifyTests.cs b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Cryptography/EcdsaVerifyTests.cs index 223878ac..70c03d13 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Cryptography/EcdsaVerifyTests.cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Cryptography/EcdsaVerifyTests.cs @@ -16,8 +16,8 @@ using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using Xunit; -using Yubico.YubiKey.Piv; using Yubico.YubiKey.Fido2.Cose; +using Yubico.YubiKey.Piv; namespace Yubico.YubiKey.Cryptography { diff --git a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Cryptography/RsaFormatNegativeTests.cs b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Cryptography/RsaFormatNegativeTests.cs index aa5e221f..f6e7268d 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Cryptography/RsaFormatNegativeTests.cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Cryptography/RsaFormatNegativeTests.cs @@ -13,10 +13,10 @@ // limitations under the License. using System; -using System.Security.Cryptography; using System.Linq; -using Yubico.YubiKey.TestUtilities; +using System.Security.Cryptography; using Xunit; +using Yubico.YubiKey.TestUtilities; namespace Yubico.YubiKey.Cryptography { diff --git a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Cryptography/RsaFormatTests.cs b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Cryptography/RsaFormatTests.cs index f2171c58..ce246076 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Cryptography/RsaFormatTests.cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Cryptography/RsaFormatTests.cs @@ -13,11 +13,11 @@ // limitations under the License. using System; -using System.Security.Cryptography; using System.Linq; +using System.Security.Cryptography; +using Xunit; using Yubico.YubiKey.Piv; using Yubico.YubiKey.TestUtilities; -using Xunit; namespace Yubico.YubiKey.Cryptography { diff --git a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Fido2/Cbor/CborMapIntTests.cs b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Fido2/Cbor/CborMapIntTests.cs index e3a00b31..1b876534 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Fido2/Cbor/CborMapIntTests.cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Fido2/Cbor/CborMapIntTests.cs @@ -79,7 +79,7 @@ public void ReadIntegers_Success(bool isSigned) Assert.True(isValid); isValid = TestUInt32(encoding, flags); Assert.True(isValid); - isValid = TestInt64 (encoding, flags); + isValid = TestInt64(encoding, flags); Assert.True(isValid); isValid = TestUInt64(encoding, flags); Assert.True(isValid); diff --git a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Fido2/Cbor/CborMapTests.cs b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Fido2/Cbor/CborMapTests.cs index ca2b78b9..d7accbf0 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Fido2/Cbor/CborMapTests.cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Fido2/Cbor/CborMapTests.cs @@ -132,7 +132,7 @@ private static bool ReadMapX1(CborReader cbor) cbor.ReadEndMap(); - return (mapKeyOne == 0x03) && (mapKeyTwo == 0x04) && (valueOne.Length == 4) && (valueTwo.Length == 2); + return mapKeyOne == 0x03 && mapKeyTwo == 0x04 && valueOne.Length == 4 && valueTwo.Length == 2; } private static bool ReadMapX2(CborReader cbor) @@ -155,7 +155,7 @@ private static bool ReadMapX2(CborReader cbor) cbor.ReadEndMap(); - return isValidOne && isValidTwo && (valueOne.Length == 4) && (valueTwo.Length == 2); + return isValidOne && isValidTwo && valueOne.Length == 4 && valueTwo.Length == 2; } private static bool ReadArrayX3(CborReader cbor) 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 5223881e..75b7a1a9 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Fido2/Commands/CredMgmtDataTests.cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Fido2/Commands/CredMgmtDataTests.cs @@ -48,7 +48,7 @@ public void CredMgm_Decode_CorrectNumCredentials() bool isCorrect = false; CredentialManagementData mgmtData = GetFullCredMgmtData(out Dictionary expectedValues); object expected = expectedValues[NumCredentials]; - if (!(mgmtData.NumberOfDiscoverableCredentials is null) && (expected is int unboxedValue)) + if (!(mgmtData.NumberOfDiscoverableCredentials is null) && expected is int unboxedValue) { isCorrect = unboxedValue == mgmtData.NumberOfDiscoverableCredentials; } @@ -62,7 +62,7 @@ public void CredMgm_Decode_CorrectRemainCount() bool isCorrect = false; CredentialManagementData mgmtData = GetFullCredMgmtData(out Dictionary expectedValues); object expected = expectedValues[RemainCount]; - if (!(mgmtData.RemainingCredentialCount is null) && (expected is int unboxedValue)) + if (!(mgmtData.RemainingCredentialCount is null) && expected is int unboxedValue) { isCorrect = unboxedValue == mgmtData.RemainingCredentialCount; } @@ -76,7 +76,7 @@ public void CredMgm_Decode_CorrectRpId() bool isCorrect = false; CredentialManagementData mgmtData = GetFullCredMgmtData(out Dictionary expectedValues); object expected = expectedValues[RpId]; - if (!(mgmtData.RelyingParty is null) && (expected is string unboxedValue)) + if (!(mgmtData.RelyingParty is null) && expected is string unboxedValue) { isCorrect = unboxedValue == mgmtData.RelyingParty.Id; } @@ -90,7 +90,7 @@ public void CredMgm_Decode_CorrectRpName() bool isCorrect = false; CredentialManagementData mgmtData = GetFullCredMgmtData(out Dictionary expectedValues); object expected = expectedValues[RpName]; - if (!(mgmtData.RelyingParty is null) && (expected is string unboxedValue)) + if (!(mgmtData.RelyingParty is null) && expected is string unboxedValue) { isCorrect = unboxedValue == mgmtData.RelyingParty.Name; } @@ -104,7 +104,7 @@ public void CredMgm_Decode_CorrectRpIdHash() bool isCorrect = false; CredentialManagementData mgmtData = GetFullCredMgmtData(out Dictionary expectedValues); object expected = expectedValues[RpIdHash]; - if (!(mgmtData.RelyingPartyIdHash is null) && (expected is byte[] unboxedValue)) + if (!(mgmtData.RelyingPartyIdHash is null) && expected is byte[] unboxedValue) { isCorrect = MemoryExtensions.SequenceEqual(mgmtData.RelyingPartyIdHash.Value.Span, unboxedValue); } @@ -118,7 +118,7 @@ public void CredMgm_Decode_CorrectRpCount() bool isCorrect = false; CredentialManagementData mgmtData = GetFullCredMgmtData(out Dictionary expectedValues); object expected = expectedValues[RpCount]; - if (!(mgmtData.TotalRelyingPartyCount is null) && (expected is int unboxedValue)) + if (!(mgmtData.TotalRelyingPartyCount is null) && expected is int unboxedValue) { isCorrect = unboxedValue == mgmtData.TotalRelyingPartyCount; } @@ -132,7 +132,7 @@ public void CredMgm_Decode_CorrectUserId() bool isCorrect = false; CredentialManagementData mgmtData = GetFullCredMgmtData(out Dictionary expectedValues); object expected = expectedValues[UserId]; - if (!(mgmtData.User is null) && (expected is byte[] unboxedValue)) + if (!(mgmtData.User is null) && expected is byte[] unboxedValue) { isCorrect = MemoryExtensions.SequenceEqual(mgmtData.User.Id.Span, unboxedValue); } @@ -146,7 +146,7 @@ public void CredMgm_Decode_CorrectUserName() bool isCorrect = false; CredentialManagementData mgmtData = GetFullCredMgmtData(out Dictionary expectedValues); object expected = expectedValues[UserName]; - if (!(mgmtData.User is null) && (expected is string unboxedValue)) + if (!(mgmtData.User is null) && expected is string unboxedValue) { isCorrect = unboxedValue == mgmtData.User.Name; } @@ -160,7 +160,7 @@ public void CredMgm_Decode_CorrectUserDisplayName() bool isCorrect = false; CredentialManagementData mgmtData = GetFullCredMgmtData(out Dictionary expectedValues); object expected = expectedValues[UserDisplayName]; - if (!(mgmtData.User is null) && (expected is string unboxedValue)) + if (!(mgmtData.User is null) && expected is string unboxedValue) { isCorrect = unboxedValue == mgmtData.User.DisplayName; } @@ -174,7 +174,7 @@ public void CredMgm_Decode_CorrectCredIdId() bool isCorrect = false; CredentialManagementData mgmtData = GetFullCredMgmtData(out Dictionary expectedValues); object expected = expectedValues[CredIdId]; - if (!(mgmtData.CredentialId is null) && (expected is byte[] unboxedValue)) + if (!(mgmtData.CredentialId is null) && expected is byte[] unboxedValue) { isCorrect = MemoryExtensions.SequenceEqual(mgmtData.CredentialId.Id.Span, unboxedValue); } @@ -188,7 +188,7 @@ public void CredMgm_Decode_CorrectCredIdType() bool isCorrect = false; CredentialManagementData mgmtData = GetFullCredMgmtData(out Dictionary expectedValues); object expected = expectedValues[CredIdType]; - if (!(mgmtData.CredentialId is null) && (expected is string unboxedValue)) + if (!(mgmtData.CredentialId is null) && expected is string unboxedValue) { isCorrect = unboxedValue == mgmtData.CredentialId.Type; } @@ -202,9 +202,9 @@ 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 null) && expected is string[] unboxedValue) { - if (!(mgmtData.CredentialId.Transports is null) && (mgmtData.CredentialId.Transports.Count == unboxedValue.Length)) + if (!(mgmtData.CredentialId.Transports is null) && mgmtData.CredentialId.Transports.Count == unboxedValue.Length) { int index = 0; for (; index < unboxedValue.Length; index++) @@ -227,7 +227,7 @@ public void CredMgm_Decode_CorrectKeyType() bool isCorrect = false; CredentialManagementData mgmtData = GetFullCredMgmtData(out Dictionary expectedValues); object expected = expectedValues[PubKeyType]; - if (!(mgmtData.CredentialPublicKey is null) && (expected is CoseKeyType unboxedValue)) + if (!(mgmtData.CredentialPublicKey is null) && expected is CoseKeyType unboxedValue) { isCorrect = unboxedValue == mgmtData.CredentialPublicKey.Type; } @@ -241,7 +241,7 @@ public void CredMgm_Decode_CorrectKeyAlg() bool isCorrect = false; CredentialManagementData mgmtData = GetFullCredMgmtData(out Dictionary expectedValues); object expected = expectedValues[PubKeyAlg]; - if (!(mgmtData.CredentialPublicKey is null) && (expected is CoseAlgorithmIdentifier unboxedValue)) + if (!(mgmtData.CredentialPublicKey is null) && expected is CoseAlgorithmIdentifier unboxedValue) { isCorrect = unboxedValue == mgmtData.CredentialPublicKey.Algorithm; } @@ -255,7 +255,7 @@ 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 null) && expected is CoseEcCurve unboxedValue) { if (mgmtData.CredentialPublicKey is CoseEcPublicKey pubKey) { @@ -272,7 +272,7 @@ 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 null) && expected is byte[] unboxedValue) { if (mgmtData.CredentialPublicKey is CoseEcPublicKey pubKey) { @@ -289,7 +289,7 @@ 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 null) && expected is byte[] unboxedValue) { if (mgmtData.CredentialPublicKey is CoseEcPublicKey pubKey) { @@ -306,7 +306,7 @@ public void CredMgm_Decode_CorrectTotalCredentialCount() bool isCorrect = false; CredentialManagementData mgmtData = GetFullCredMgmtData(out Dictionary expectedValues); object expected = expectedValues[TotalCount]; - if (!(mgmtData.TotalCredentialsForRelyingParty is null) && (expected is int unboxedValue)) + if (!(mgmtData.TotalCredentialsForRelyingParty is null) && expected is int unboxedValue) { isCorrect = unboxedValue == mgmtData.TotalCredentialsForRelyingParty; } @@ -320,7 +320,7 @@ public void CredMgm_Decode_CorrectCredProtectPolicy() bool isCorrect = false; CredentialManagementData mgmtData = GetFullCredMgmtData(out Dictionary expectedValues); object expected = expectedValues[CredProtect]; - if (!(mgmtData.CredProtectPolicy is null) && (expected is int unboxedValue)) + if (!(mgmtData.CredProtectPolicy is null) && expected is int unboxedValue) { isCorrect = unboxedValue == mgmtData.CredProtectPolicy; } @@ -334,7 +334,7 @@ public void CredMgm_Decode_CorrectLargeBlobKey() bool isCorrect = false; CredentialManagementData mgmtData = GetFullCredMgmtData(out Dictionary expectedValues); object expected = expectedValues[BlobKey]; - if (!(mgmtData.LargeBlobKey is null) && (expected is byte[] unboxedValue)) + if (!(mgmtData.LargeBlobKey is null) && expected is byte[] unboxedValue) { isCorrect = MemoryExtensions.SequenceEqual(mgmtData.LargeBlobKey.Value.Span, unboxedValue); } diff --git a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Fido2/CredentialDataTests.cs b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Fido2/CredentialDataTests.cs index e2bd2287..4bf3fedf 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Fido2/CredentialDataTests.cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Fido2/CredentialDataTests.cs @@ -16,11 +16,11 @@ using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using Xunit; +using Yubico.Core.Tlv; +using Yubico.YubiKey.Cryptography; using Yubico.YubiKey.Fido2.Commands; using Yubico.YubiKey.Fido2.Cose; -using Yubico.YubiKey.Cryptography; using Yubico.YubiKey.Piv; -using Yubico.Core.Tlv; namespace Yubico.YubiKey.Fido2 { diff --git a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Fido2/Fido2InfoTests.cs b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Fido2/Fido2InfoTests.cs index b5d42ed6..2e1992c4 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Fido2/Fido2InfoTests.cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Fido2/Fido2InfoTests.cs @@ -640,79 +640,79 @@ private static bool CompareStringLists(string[] correctStrings, IReadOnlyList data = command.CreateCommandApdu().Data; Assert.True(data.Span.SequenceEqual(newDataList)); @@ -130,7 +130,7 @@ public void CreateResponseApdu_ReturnsCorrectType() { var responseApdu = new ResponseApdu(new byte[] { 0x90, 0x00 }); var command = new CalculateAllCredentialsCommand(); - var response = command.CreateResponseForApdu(responseApdu); + CalculateAllCredentialsResponse? response = command.CreateResponseForApdu(responseApdu); Assert.True(response is CalculateAllCredentialsResponse); } diff --git a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Oath/Commands/CalculateAllCredentialsResponseTests.cs b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Oath/Commands/CalculateAllCredentialsResponseTests.cs index 3de388f6..b3dea57e 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Oath/Commands/CalculateAllCredentialsResponseTests.cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Oath/Commands/CalculateAllCredentialsResponseTests.cs @@ -27,7 +27,7 @@ public void Status_SuccessResponseApdu_ReturnsSuccess() const byte sw2 = unchecked((byte)SWConstants.Success); var responseApdu = new ResponseApdu(new byte[] { sw1, sw2 }); - + var calculateAllCredentialsResponse = new CalculateAllCredentialsResponse(responseApdu); Assert.Equal(ResponseStatus.Success, calculateAllCredentialsResponse.Status); @@ -40,7 +40,7 @@ public void SuccessResponseApdu_NoCredentials_ListCredentialsCorrectly() const byte sw2 = unchecked((byte)SWConstants.Success); var responseApdu = new ResponseApdu(new byte[] { sw1, sw2 }); - + var calculateAllCredentialsResponse = new CalculateAllCredentialsResponse(responseApdu); Assert.Equal(SWConstants.Success, calculateAllCredentialsResponse.StatusWord); @@ -53,12 +53,12 @@ public void Constructor_SuccessResponseApdu_NoCredentials_ReturnResponseCorrectl const byte sw2 = unchecked((byte)SWConstants.Success); var responseApdu = new ResponseApdu(new byte[] { sw1, sw2 }); - + var calculateAllCredentialsResponse = new CalculateAllCredentialsResponse(responseApdu); - var data = calculateAllCredentialsResponse.GetData(); + System.Collections.Generic.IDictionary? data = calculateAllCredentialsResponse.GetData(); Assert.Equal(SWConstants.Success, calculateAllCredentialsResponse.StatusWord); - Assert.Empty(data); + Assert.Empty(data); } [Fact] @@ -77,9 +77,10 @@ public void Constructor_SuccessResponseApdu_ReturnResponseCorrectly() var calculateAllCredentialsResponse = new CalculateAllCredentialsResponse(responseApdu); - var data = calculateAllCredentialsResponse.GetData(); + System.Collections.Generic.IDictionary? data = calculateAllCredentialsResponse.GetData(); var credentialHotp = new Credential("Apple", "test@icloud.com", CredentialType.Hotp, CredentialPeriod.Undefined); - var credentialTotp = new Credential { + var credentialTotp = new Credential + { Issuer = "Microsoft", AccountName = "test@outlook.com", Type = CredentialType.Totp, diff --git a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Oath/Commands/CalculateCredentialCommandTests.cs b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Oath/Commands/CalculateCredentialCommandTests.cs index 105c8a9f..0699cfac 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Oath/Commands/CalculateCredentialCommandTests.cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Oath/Commands/CalculateCredentialCommandTests.cs @@ -13,13 +13,13 @@ // limitations under the License. using System; +using System.Buffers.Binary; using System.Linq; using System.Security.Cryptography; using Xunit; -using Yubico.YubiKey.TestUtilities; using Yubico.Core.Iso7816; using Yubico.YubiKey.Cryptography; -using System.Buffers.Binary; +using Yubico.YubiKey.TestUtilities; namespace Yubico.YubiKey.Oath.Commands { @@ -93,7 +93,7 @@ public void CreateCommandApdu_TotpCredential_ReturnsCorrectLength() }; byte[] challenge = GenerateChallenge(_credential.Period); - var newDataList = dataList.Concat(challenge).ToArray(); + byte[]? newDataList = dataList.Concat(challenge).ToArray(); ReadOnlyMemory data = command.CreateCommandApdu().Data; Assert.Equal(newDataList.Length, command.CreateCommandApdu().Nc); @@ -119,11 +119,11 @@ public void CreateCommandApdu_TotpCredential_ReturnsCorrectData() 0x74, 0x3A, 0x74, 0x65, 0x73, 0x74, 0x40, 0x6F, 0x75, 0x74, 0x6C, 0x6F, 0x6F, 0x6B, 0x2E, 0x63, 0x6F, 0x6D, 0x74, 0x08, }; - + byte[] challenge = GenerateChallenge(_credential.Period); - var newDataList = dataList.Concat(challenge).ToArray(); + byte[]? newDataList = dataList.Concat(challenge).ToArray(); ReadOnlyMemory data = command.CreateCommandApdu().Data; - + Assert.True(data.Span.SequenceEqual(newDataList)); } finally @@ -148,7 +148,7 @@ public void CreateCommandApdu_HotpCredential_ReturnsCorrectDataAndLength() }; ReadOnlyMemory data = command.CreateCommandApdu().Data; - + Assert.Equal(dataList.Length, command.CreateCommandApdu().Nc); Assert.True(data.Span.SequenceEqual(dataList)); } @@ -158,17 +158,14 @@ public void CreateResponseApdu_ReturnsCorrectType() { var responseApdu = new ResponseApdu(new byte[] { 0x90, 0x00 }); var command = new CalculateCredentialCommand(_credential, ResponseFormat.Full); - var response = command.CreateResponseForApdu(responseApdu); + CalculateCredentialResponse? response = command.CreateResponseForApdu(responseApdu); Assert.True(response is CalculateCredentialResponse); } - + private byte[] GenerateChallenge(CredentialPeriod? period) { - if (period is null) - { - period = CredentialPeriod.Period30; - } + period ??= CredentialPeriod.Period30; ulong timePeriod = (uint)DateTimeOffset.UtcNow.ToUnixTimeSeconds() / (uint)period; byte[] bytes = new byte[8]; diff --git a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Oath/Commands/CalculateCredentialResponseTests .cs b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Oath/Commands/CalculateCredentialResponseTests .cs index 68288e98..05b22096 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Oath/Commands/CalculateCredentialResponseTests .cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Oath/Commands/CalculateCredentialResponseTests .cs @@ -77,7 +77,7 @@ public void Constructor_SuccessResponseApdu_FullResponse_ReturnResponseCorrectly var calculateCredentialResponse = new CalculateCredentialResponse(responseApdu, credential); - var data = calculateCredentialResponse.GetData(); + Code? data = calculateCredentialResponse.GetData(); Assert.Equal(SWConstants.Success, calculateCredentialResponse.StatusWord); Assert.NotNull(data.Value); @@ -96,7 +96,7 @@ public void Constructor_SuccessResponseApdu_TruncatedResponse_ReturnResponseCorr var calculateCredentialResponse = new CalculateCredentialResponse(responseApdu, credential); - var data = calculateCredentialResponse.GetData(); + Code? data = calculateCredentialResponse.GetData(); Assert.Equal(SWConstants.Success, calculateCredentialResponse.StatusWord); Assert.NotNull(data.Value); diff --git a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Oath/Commands/DeleteCredentialCommandTests.cs b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Oath/Commands/DeleteCredentialCommandTests.cs index 5d5ab20a..e6842e9d 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Oath/Commands/DeleteCredentialCommandTests.cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Oath/Commands/DeleteCredentialCommandTests.cs @@ -20,7 +20,7 @@ namespace Yubico.YubiKey.Oath.Commands { public class DeleteCredentialCommandTests { - Credential credential = new Credential("Microsoft", "test@outlook.com", CredentialType.Totp, HashAlgorithm.Sha1, "tt", CredentialPeriod.Period30, 6, 0, false); + readonly Credential credential = new Credential("Microsoft", "test@outlook.com", CredentialType.Totp, HashAlgorithm.Sha1, "tt", CredentialPeriod.Period30, 6, 0, false); [Fact] public void CreateCommandApdu_GetClaProperty_ReturnsZero() @@ -58,7 +58,7 @@ public void CreateCommandApdu_GetP2Property_ReturnsZero() public void CreateCommandApdu_ReturnsCorrectDataAndLength() { var command = new DeleteCommand { Credential = credential }; - byte[] dataList = + byte[] dataList = { 0x71, 0x1A, 0x4D, 0x69, 0x63, 0x72, 0x6F, 0x73, 0x6F, 0x66, 0x74, 0x3A, 0x74, 0x65, 0x73, 0x74, 0x40, 0x6F, 0x75, 0x74, @@ -76,7 +76,7 @@ public void CreateResponseApdu_ReturnsCorrectType() { var responseApdu = new ResponseApdu(new byte[] { 0x90, 0x00 }); var command = new DeleteCommand { Credential = credential }; - var response = command.CreateResponseForApdu(responseApdu); + DeleteResponse? response = command.CreateResponseForApdu(responseApdu); Assert.True(response is DeleteResponse); } diff --git a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Oath/Commands/ListCredentialsCommandTests.cs b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Oath/Commands/ListCredentialsCommandTests.cs index b74de371..0d3ef059 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Oath/Commands/ListCredentialsCommandTests.cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Oath/Commands/ListCredentialsCommandTests.cs @@ -40,7 +40,7 @@ public void CreateCommandApdu_GetInsProperty_Returns0xa1() public void CreateCommandApdu_GetP1Property_ReturnsZero() { var command = new ListCommand(); - + Assert.Equal(0, command.CreateCommandApdu().P1); } @@ -58,7 +58,7 @@ public void CreateCommandApdu_GetData_ReturnsEmpty() var command = new ListCommand(); ReadOnlyMemory data = command.CreateCommandApdu().Data; - + Assert.True(data.IsEmpty); } @@ -83,7 +83,7 @@ public void CreateResponseApdu_ReturnsCorrectType() { var responseApdu = new ResponseApdu(new byte[] { 0x90, 0x00 }); var command = new ListCommand(); - var response = command.CreateResponseForApdu(responseApdu); + ListResponse? response = command.CreateResponseForApdu(responseApdu); Assert.True(response is ListResponse); } diff --git a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Oath/Commands/ListCredentialsResponseTests.cs b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Oath/Commands/ListCredentialsResponseTests.cs index eb161a34..6362117f 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Oath/Commands/ListCredentialsResponseTests.cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Oath/Commands/ListCredentialsResponseTests.cs @@ -43,7 +43,7 @@ public void SuccessResponseApdu_NoCredentials_ListCredentialsCorrectly() var listCredentialsResponse = new ListResponse(responseApdu); - var data = listCredentialsResponse.GetData(); + System.Collections.Generic.List? data = listCredentialsResponse.GetData(); Assert.Empty(data); Assert.Equal(SWConstants.Success, listCredentialsResponse.StatusWord); @@ -64,7 +64,7 @@ public void Constructor_SuccessResponseApdu_OneCredential_ListCredentialsCorrect var listCredentialsResponse = new ListResponse(responseApdu); - var data = listCredentialsResponse.GetData(); + System.Collections.Generic.List? data = listCredentialsResponse.GetData(); Assert.Equal(SWConstants.Success, listCredentialsResponse.StatusWord); @@ -96,7 +96,7 @@ public void Constructor_SuccessResponseApdu_Totp30sAccountMaxLength_ListCredenti var listCredentialsResponse = new ListResponse(responseApdu); - var data = listCredentialsResponse.GetData(); + System.Collections.Generic.List? data = listCredentialsResponse.GetData(); Assert.Equal(SWConstants.Success, listCredentialsResponse.StatusWord); @@ -121,7 +121,7 @@ public void Constructor_SuccessResponseApdu_OneCredentialNoIssuer_ListCredential var listCredentialsResponse = new ListResponse(responseApdu); - var data = listCredentialsResponse.GetData(); + System.Collections.Generic.List? data = listCredentialsResponse.GetData(); Assert.Equal(SWConstants.Success, listCredentialsResponse.StatusWord); @@ -143,15 +143,15 @@ public void Constructor_SuccessResponseApdu_MultipleCredentials_ListCredentialsC var responseApdu = new ResponseApdu(new byte[] { 0x72, 0x1B, 0x21, 0x4D, 0x69, 0x63, 0x72, 0x6F, 0x73, 0x6F, 0x66, 0x74, 0x3A, 0x74, 0x65, 0x73, 0x74, 0x40, 0x6F, 0x75, - 0x74, 0x6C, 0x6F, 0x6F, 0x6B, 0x2E, 0x63, 0x6F, 0x6D, 0x72, - 0x16, 0x12, 0x47, 0x6F, 0x6F, 0x67, 0x6C, 0x65, 0x3A, 0x74, + 0x74, 0x6C, 0x6F, 0x6F, 0x6B, 0x2E, 0x63, 0x6F, 0x6D, 0x72, + 0x16, 0x12, 0x47, 0x6F, 0x6F, 0x67, 0x6C, 0x65, 0x3A, 0x74, 0x65, 0x73, 0x74, 0x40, 0x67, 0x6D, 0x61, 0x69, 0x6C, 0x2E, 0x63, 0x6F, 0x6D, sw1, sw2 }); var listCredentialsResponse = new ListResponse(responseApdu); - var data = listCredentialsResponse.GetData(); + System.Collections.Generic.List? data = listCredentialsResponse.GetData(); Assert.Equal(SWConstants.Success, listCredentialsResponse.StatusWord); @@ -178,14 +178,14 @@ public void Constructor_SuccessResponseApdu_Period60_ListCredentialsCorrectly() var responseApdu = new ResponseApdu(new byte[] { 0x72, 0x1E, 0x21, 0x36, 0x30, 0x2F, 0x4D, 0x69, 0x63, 0x72, - 0x6F, 0x73, 0x6F, 0x66, 0x74, 0x3A, 0x74, 0x65, 0x73, 0x74, - 0x40, 0x6F, 0x75, 0x74, 0x6C, 0x6F, 0x6F, 0x6B, 0x2E, 0x63, + 0x6F, 0x73, 0x6F, 0x66, 0x74, 0x3A, 0x74, 0x65, 0x73, 0x74, + 0x40, 0x6F, 0x75, 0x74, 0x6C, 0x6F, 0x6F, 0x6B, 0x2E, 0x63, 0x6F, 0x6D, sw1, sw2 }); var listCredentialsResponse = new ListResponse(responseApdu); - var data = listCredentialsResponse.GetData(); + System.Collections.Generic.List? data = listCredentialsResponse.GetData(); Assert.Equal(SWConstants.Success, listCredentialsResponse.StatusWord); @@ -212,7 +212,7 @@ public void Constructor_SuccessResponseApdu_IssuerHasSemicolon_ListCredentialsCo var listCredentialsResponse = new ListResponse(responseApdu); - var data = listCredentialsResponse.GetData(); + System.Collections.Generic.List? data = listCredentialsResponse.GetData(); Assert.Equal(SWConstants.Success, listCredentialsResponse.StatusWord); diff --git a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Oath/Commands/RenameCredentialCommandTests.cs b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Oath/Commands/RenameCredentialCommandTests.cs index d2f4839c..c606045c 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Oath/Commands/RenameCredentialCommandTests.cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Oath/Commands/RenameCredentialCommandTests.cs @@ -60,7 +60,7 @@ public void CreateCommandApdu_GetP2Property_ReturnsZero() public void CreateCommandApdu_ReturnsCorrectDataAndLength() { var command = new RenameCommand(credential, newIssuer, newAccount); - byte[] dataList = + byte[] dataList = { 0x71, 0x1A, 0x4D, 0x69, 0x63, 0x72, 0x6F, 0x73, 0x6F, 0x66, 0x74, 0x3A, 0x74, 0x65, 0x73, 0x74, 0x40, 0x6F, 0x75, 0x74, @@ -82,7 +82,7 @@ public void CreateResponseApdu_ReturnsCorrectType() { var responseApdu = new ResponseApdu(new byte[] { 0x90, 0x00 }); var command = new RenameCommand(credential, newIssuer, newAccount); - var response = command.CreateResponseForApdu(responseApdu); + RenameResponse? response = command.CreateResponseForApdu(responseApdu); Assert.True(response is RenameResponse); } diff --git a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Oath/Commands/ResetApplicationCommandTests .cs b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Oath/Commands/ResetApplicationCommandTests .cs index 2660d609..07f63c4c 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Oath/Commands/ResetApplicationCommandTests .cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Oath/Commands/ResetApplicationCommandTests .cs @@ -75,7 +75,7 @@ public void CreateResponseApdu_ReturnsCorrectType() { var responseApdu = new ResponseApdu(new byte[] { 0x90, 0x00 }); var command = new ResetCommand(); - var response = command.CreateResponseForApdu(responseApdu); + OathResponse? response = command.CreateResponseForApdu(responseApdu); Assert.True(response is OathResponse); } diff --git a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Oath/Commands/SelectOathCommandTests.cs b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Oath/Commands/SelectOathCommandTests.cs index ef6540b2..9e13a628 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Oath/Commands/SelectOathCommandTests.cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Oath/Commands/SelectOathCommandTests.cs @@ -67,7 +67,7 @@ public void CreateResponseApdu_ReturnsCorrectType() { var command = new SelectOathCommand(); var responseApdu = new ResponseApdu(new byte[] { 0x90, 0x00 }); - var response = command.CreateResponseForApdu(responseApdu); + SelectOathResponse? response = command.CreateResponseForApdu(responseApdu); Assert.True(response is SelectOathResponse); } diff --git a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Oath/Commands/SelectOathResponseTests.cs b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Oath/Commands/SelectOathResponseTests.cs index 02a7acf3..8ba25ddc 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Oath/Commands/SelectOathResponseTests.cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Oath/Commands/SelectOathResponseTests.cs @@ -47,8 +47,8 @@ public void SuccessResponseApdu_PasswordIsSet_OathResponseInfoCorrect() }); var selectOathResponse = new SelectOathResponse(responseApdu); - var data = selectOathResponse.GetData(); - + OathApplicationData? data = selectOathResponse.GetData(); + var version = new FirmwareVersion { Major = 0x05, @@ -56,9 +56,9 @@ public void SuccessResponseApdu_PasswordIsSet_OathResponseInfoCorrect() Patch = 0x04 }; - var salt = new byte[] { 0xE3, 0x0E, 0xB3, 0x36, 0x5C, 0x8D, 0xF1, 0x44 }; - var challenge = new byte[] { 0xF1, 0xD3, 0xDA, 0x89, 0x58, 0xE4, 0x40, 0x85 }; - var algorithm = HashAlgorithm.Sha1; + byte[]? salt = new byte[] { 0xE3, 0x0E, 0xB3, 0x36, 0x5C, 0x8D, 0xF1, 0x44 }; + byte[]? challenge = new byte[] { 0xF1, 0xD3, 0xDA, 0x89, 0x58, 0xE4, 0x40, 0x85 }; + HashAlgorithm algorithm = HashAlgorithm.Sha1; Assert.Equal(SWConstants.Success, selectOathResponse.StatusWord); Assert.Equal(version, data.Version); @@ -80,7 +80,7 @@ public void Constructor_SuccessResponseApdu_NoPasswordSet_OathResponseInfoCorrec var selectOathResponse = new SelectOathResponse(responseApdu); - var data = selectOathResponse.GetData(); + OathApplicationData? data = selectOathResponse.GetData(); var version = new FirmwareVersion { @@ -89,8 +89,8 @@ public void Constructor_SuccessResponseApdu_NoPasswordSet_OathResponseInfoCorrec Patch = 0x04 }; - var salt = new byte[] { 0xC0, 0xE3, 0xAF, 0x27, 0xCC, 0x7A, 0x20, 0xEE }; - var algorithm = HashAlgorithm.Sha1; + byte[]? salt = new byte[] { 0xC0, 0xE3, 0xAF, 0x27, 0xCC, 0x7A, 0x20, 0xEE }; + HashAlgorithm algorithm = HashAlgorithm.Sha1; Assert.Equal(SWConstants.Success, selectOathResponse.StatusWord); Assert.Equal(version, data.Version); diff --git a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Oath/Commands/SetPasswordCommandTests.cs b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Oath/Commands/SetPasswordCommandTests.cs index 94ba7cf7..ad0095f3 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Oath/Commands/SetPasswordCommandTests.cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Oath/Commands/SetPasswordCommandTests.cs @@ -17,9 +17,9 @@ using System.Security.Cryptography; using System.Text; using Xunit; -using Yubico.YubiKey.TestUtilities; using Yubico.Core.Iso7816; using Yubico.YubiKey.Cryptography; +using Yubico.YubiKey.TestUtilities; namespace Yubico.YubiKey.Oath.Commands { diff --git a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Oath/Commands/ValidateCommandTests.cs b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Oath/Commands/ValidateCommandTests.cs index ecf0cdf7..af7d765e 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Oath/Commands/ValidateCommandTests.cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Oath/Commands/ValidateCommandTests.cs @@ -16,9 +16,9 @@ using System.Security.Cryptography; using System.Text; using Xunit; -using Yubico.YubiKey.TestUtilities; using Yubico.Core.Iso7816; using Yubico.YubiKey.Cryptography; +using Yubico.YubiKey.TestUtilities; namespace Yubico.YubiKey.Oath.Commands { @@ -31,7 +31,7 @@ public class ValidateCommandTests private readonly ResponseApdu selectResponseApdu = new ResponseApdu(new byte[] { 0x79, 0x03, 0x05, 0x02, 0x04, 0x71, 0x08, 0xC0, 0xE3, 0xAF, - 0x27, 0xCC, 0x7A, 0x20, 0xEE, 0x74, 0x08, 0xF1, 0x03, 0xDA, + 0x27, 0xCC, 0x7A, 0x20, 0xEE, 0x74, 0x08, 0xF1, 0x03, 0xDA, 0x89, 0x58, 0xE4, 0x40, 0x85, 0x7B, 0x01, 0x01, sw1, sw2 }); diff --git a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Oath/Commands/ValidateResponseTests.cs b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Oath/Commands/ValidateResponseTests.cs index 971ded07..d4694fac 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Oath/Commands/ValidateResponseTests.cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Oath/Commands/ValidateResponseTests.cs @@ -17,9 +17,9 @@ using System.Security.Cryptography; using System.Text; using Xunit; -using Yubico.YubiKey.TestUtilities; using Yubico.Core.Iso7816; using Yubico.YubiKey.Cryptography; +using Yubico.YubiKey.TestUtilities; namespace Yubico.YubiKey.Oath.Commands { diff --git a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Oath/CredentialTests.cs b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Oath/CredentialTests.cs index e0a95059..f64beb37 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Oath/CredentialTests.cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Oath/CredentialTests.cs @@ -35,9 +35,10 @@ public void Issuer_GetDefaultValue_ReturnsNull() [Fact] public void Issuer_SetToTestString_ReturnsTestString() { - Credential cred = new Credential(); - - cred.Issuer = DefaultTestIssuer; + Credential cred = new Credential + { + Issuer = DefaultTestIssuer + }; string? actualIssuer = cred.Issuer; Assert.Equal(DefaultTestIssuer, actualIssuer); @@ -58,9 +59,10 @@ public void Issuer_SetToTestStringWithLeadingTrailingWhiteSpace_ReturnsTestStrin [Fact] public void Issuer_SetToNull_ReturnsNull() { - Credential cred = new Credential(); - - cred.Issuer = null; + Credential cred = new Credential + { + Issuer = null + }; string? actualIssuer = cred.Issuer; Assert.Null(actualIssuer); @@ -69,9 +71,10 @@ public void Issuer_SetToNull_ReturnsNull() [Fact] public void Issuer_SetToEmptyString_ReturnsNull() { - Credential cred = new Credential(); - - cred.Issuer = string.Empty; + Credential cred = new Credential + { + Issuer = string.Empty + }; string? actualIssuer = cred.Issuer; Assert.Null(actualIssuer); @@ -83,9 +86,10 @@ public void Issuer_SetToEmptyString_ReturnsNull() [InlineData("\u2000\u2000\u2000")] public void Issuer_SetToWhiteSpace_ReturnsNull(string? issuerValue) { - Credential cred = new Credential(); - - cred.Issuer = issuerValue; + Credential cred = new Credential + { + Issuer = issuerValue + }; string? actualIssuer = cred.Issuer; Assert.Null(actualIssuer); @@ -98,12 +102,13 @@ public void Issuer_SetToWhiteSpace_ReturnsNull(string? issuerValue) [Fact] public void Name_Totp15sIssuerAccount_ReturnsCorrectName() { - Credential cred = new Credential(); - - cred.Type = CredentialType.Totp; - cred.Period = CredentialPeriod.Period15; - cred.Issuer = DefaultTestIssuer; - cred.AccountName = DefaultTestAccount; + Credential cred = new Credential + { + Type = CredentialType.Totp, + Period = CredentialPeriod.Period15, + Issuer = DefaultTestIssuer, + AccountName = DefaultTestAccount + }; string expectedName = $"15/{DefaultTestIssuer}:{DefaultTestAccount}"; @@ -114,12 +119,13 @@ public void Name_Totp15sIssuerAccount_ReturnsCorrectName() [Fact] public void Name_Totp30sIssuerAccount_ReturnsCorrectName() { - Credential cred = new Credential(); - - cred.Type = CredentialType.Totp; - cred.Period = CredentialPeriod.Period30; - cred.Issuer = DefaultTestIssuer; - cred.AccountName = DefaultTestAccount; + Credential cred = new Credential + { + Type = CredentialType.Totp, + Period = CredentialPeriod.Period30, + Issuer = DefaultTestIssuer, + AccountName = DefaultTestAccount + }; string expectedName = $"{DefaultTestIssuer}:{DefaultTestAccount}"; @@ -130,11 +136,12 @@ public void Name_Totp30sIssuerAccount_ReturnsCorrectName() [Fact] public void Name_HotpIssuerAccount_ReturnsCorrectName() { - Credential cred = new Credential(); - - cred.Type = CredentialType.Hotp; - cred.Issuer = DefaultTestIssuer; - cred.AccountName = DefaultTestAccount; + Credential cred = new Credential + { + Type = CredentialType.Hotp, + Issuer = DefaultTestIssuer, + AccountName = DefaultTestAccount + }; string expectedName = $"{DefaultTestIssuer}:{DefaultTestAccount}"; @@ -148,12 +155,13 @@ public void Name_HotpIssuerAccount_ReturnsCorrectName() [InlineData(" ")] public void Name_Totp15sAccount_ReturnsCorrectName(string? issuerValue) { - Credential cred = new Credential(); - - cred.Type = CredentialType.Totp; - cred.Period = CredentialPeriod.Period15; - cred.Issuer = issuerValue; - cred.AccountName = DefaultTestAccount; + Credential cred = new Credential + { + Type = CredentialType.Totp, + Period = CredentialPeriod.Period15, + Issuer = issuerValue, + AccountName = DefaultTestAccount + }; string expectedName = $"15/{DefaultTestAccount}"; @@ -164,11 +172,12 @@ public void Name_Totp15sAccount_ReturnsCorrectName(string? issuerValue) [Fact] public void Name_Totp15sAccountDefaultIssuer_ReturnsCorrectName() { - Credential cred = new Credential(); - - cred.Type = CredentialType.Totp; - cred.Period = CredentialPeriod.Period15; - cred.AccountName = DefaultTestAccount; + Credential cred = new Credential + { + Type = CredentialType.Totp, + Period = CredentialPeriod.Period15, + AccountName = DefaultTestAccount + }; string expectedName = $"15/{DefaultTestAccount}"; @@ -182,12 +191,13 @@ public void Name_Totp15sAccountDefaultIssuer_ReturnsCorrectName() [InlineData(" ")] public void Name_Totp30sAccount_ReturnsCorrectName(string? issuerValue) { - Credential cred = new Credential(); - - cred.Type = CredentialType.Totp; - cred.Period = CredentialPeriod.Period30; - cred.Issuer = issuerValue; - cred.AccountName = DefaultTestAccount; + Credential cred = new Credential + { + Type = CredentialType.Totp, + Period = CredentialPeriod.Period30, + Issuer = issuerValue, + AccountName = DefaultTestAccount + }; string expectedName = $"{DefaultTestAccount}"; @@ -198,11 +208,12 @@ public void Name_Totp30sAccount_ReturnsCorrectName(string? issuerValue) [Fact] public void Name_Totp30sAccountDefaultIssuer_ReturnsCorrectName() { - Credential cred = new Credential(); - - cred.Type = CredentialType.Totp; - cred.Period = CredentialPeriod.Period30; - cred.AccountName = DefaultTestAccount; + Credential cred = new Credential + { + Type = CredentialType.Totp, + Period = CredentialPeriod.Period30, + AccountName = DefaultTestAccount + }; string expectedName = $"{DefaultTestAccount}"; @@ -216,11 +227,12 @@ public void Name_Totp30sAccountDefaultIssuer_ReturnsCorrectName() [InlineData(" ")] public void Name_HotpAccount_ReturnsCorrectName(string? issuerValue) { - Credential cred = new Credential(); - - cred.Type = CredentialType.Hotp; - cred.Issuer = issuerValue; - cred.AccountName = DefaultTestAccount; + Credential cred = new Credential + { + Type = CredentialType.Hotp, + Issuer = issuerValue, + AccountName = DefaultTestAccount + }; string expectedName = $"{DefaultTestAccount}"; @@ -231,10 +243,11 @@ public void Name_HotpAccount_ReturnsCorrectName(string? issuerValue) [Fact] public void Name_HotpAccountDefaultIssuer_ReturnsCorrectName() { - Credential cred = new Credential(); - - cred.Type = CredentialType.Hotp; - cred.AccountName = DefaultTestAccount; + Credential cred = new Credential + { + Type = CredentialType.Hotp, + AccountName = DefaultTestAccount + }; string expectedName = $"{DefaultTestAccount}"; @@ -252,12 +265,13 @@ public void Name_HotpAccountDefaultIssuer_ReturnsCorrectName() [InlineData(CredentialType.Hotp, CredentialPeriod.Undefined, null, "1234567890123456789012345678901234567890123456789012345678901234")] public void Name_64ByteNameLength_ReturnsCorrectName(CredentialType credType, CredentialPeriod credPeriod, string? issuer, string account) { - Credential cred = new Credential(); - - cred.Type = credType; - cred.Period = credPeriod; - cred.Issuer = issuer; - cred.AccountName = account; + Credential cred = new Credential + { + Type = credType, + Period = credPeriod, + Issuer = issuer, + AccountName = account + }; string actualCredName = cred.Name; @@ -277,12 +291,13 @@ public void Name_64ByteNameLength_ReturnsCorrectName(CredentialType credType, Cr [InlineData(CredentialType.Hotp, CredentialPeriod.Undefined, null, "12345678901234567890123456789012345678901234567890123456789012345")] public void Name_65ByteNameLength_ThrowsInvalidOperationException(CredentialType credType, CredentialPeriod credPeriod, string? issuer, string account) { - Credential cred = new Credential(); - - cred.Type = credType; - cred.Period = credPeriod; - cred.Issuer = issuer; - cred.AccountName = account; + Credential cred = new Credential + { + Type = credType, + Period = credPeriod, + Issuer = issuer, + AccountName = account + }; _ = Assert.Throws(() => cred.Name); } @@ -290,10 +305,11 @@ public void Name_65ByteNameLength_ThrowsInvalidOperationException(CredentialType [Fact] public void Name_CredTypeDefault_ThrowsInvalidOperationException() { - Credential cred = new Credential(); - - cred.Issuer = DefaultTestIssuer; - cred.AccountName = DefaultTestAccount; + Credential cred = new Credential + { + Issuer = DefaultTestIssuer, + AccountName = DefaultTestAccount + }; _ = Assert.Throws(() => cred.Name); } @@ -301,11 +317,12 @@ public void Name_CredTypeDefault_ThrowsInvalidOperationException() [Fact] public void Name_CredTypeNone_ThrowsInvalidOperationException() { - Credential cred = new Credential(); - - cred.Type = CredentialType.None; - cred.Issuer = DefaultTestIssuer; - cred.AccountName = DefaultTestAccount; + Credential cred = new Credential + { + Type = CredentialType.None, + Issuer = DefaultTestIssuer, + AccountName = DefaultTestAccount + }; _ = Assert.Throws(() => cred.Name); } @@ -313,11 +330,12 @@ public void Name_CredTypeNone_ThrowsInvalidOperationException() [Fact] public void Name_TotpCredPeriodDefault_ThrowsInvalidOperationException() { - Credential cred = new Credential(); - - cred.Type = CredentialType.Totp; - cred.Issuer = DefaultTestIssuer; - cred.AccountName = DefaultTestAccount; + Credential cred = new Credential + { + Type = CredentialType.Totp, + Issuer = DefaultTestIssuer, + AccountName = DefaultTestAccount + }; _ = Assert.Throws(() => cred.Name); } @@ -325,12 +343,13 @@ public void Name_TotpCredPeriodDefault_ThrowsInvalidOperationException() [Fact] public void Name_TotpCredPeriodUndefined_ThrowsInvalidOperationException() { - Credential cred = new Credential(); - - cred.Period = CredentialPeriod.Undefined; - cred.Type = CredentialType.Totp; - cred.Issuer = DefaultTestIssuer; - cred.AccountName = DefaultTestAccount; + Credential cred = new Credential + { + Period = CredentialPeriod.Undefined, + Type = CredentialType.Totp, + Issuer = DefaultTestIssuer, + AccountName = DefaultTestAccount + }; _ = Assert.Throws(() => cred.Name); } @@ -338,11 +357,12 @@ public void Name_TotpCredPeriodUndefined_ThrowsInvalidOperationException() [Fact] public void Name_Totp30sAccountDefault_ThrowsInvalidOperationException() { - Credential cred = new Credential(); - - cred.Type = CredentialType.Totp; - cred.Period = CredentialPeriod.Period30; - cred.Issuer = DefaultTestIssuer; + Credential cred = new Credential + { + Type = CredentialType.Totp, + Period = CredentialPeriod.Period30, + Issuer = DefaultTestIssuer + }; _ = Assert.Throws(() => cred.Name); } @@ -350,10 +370,11 @@ public void Name_Totp30sAccountDefault_ThrowsInvalidOperationException() [Fact] public void Name_HotpAccountDefault_ThrowsInvalidOperationException() { - Credential cred = new Credential(); - - cred.Type = CredentialType.Hotp; - cred.Issuer = DefaultTestIssuer; + Credential cred = new Credential + { + Type = CredentialType.Hotp, + Issuer = DefaultTestIssuer + }; _ = Assert.Throws(() => cred.Name); } @@ -363,8 +384,8 @@ public void Name_HotpAccountDefault_ThrowsInvalidOperationException() [Fact] public void CredentialIssuerAndAccount_UriUnescape_ReturnsCorrectUnescapedStrings() { - var issuer = Uri.UnescapeDataString("Microsoft%3Ademo"); - var account = Uri.UnescapeDataString("test%40outlook.com"); + string? issuer = Uri.UnescapeDataString("Microsoft%3Ademo"); + string? account = Uri.UnescapeDataString("test%40outlook.com"); Assert.Equal("Microsoft:demo", issuer); Assert.Equal("test@outlook.com", account); @@ -373,78 +394,78 @@ public void CredentialIssuerAndAccount_UriUnescape_ReturnsCorrectUnescapedString [Fact] public void CredentialParseLabel_TotpTypeAndDefaultPeriod_ReturnsCorrectlyParsedLabel() { - var label = "Microsoft:demo:test@outlook.com"; - var parsedLabel = Credential.ParseLabel(label, CredentialType.Totp); - - Assert.Equal(CredentialPeriod.Period30, parsedLabel.period); - Assert.Equal("Microsoft:demo", parsedLabel.issuer); - Assert.Equal("test@outlook.com", parsedLabel.account); + string? label = "Microsoft:demo:test@outlook.com"; + (CredentialPeriod period, string? issuer, string account) = Credential.ParseLabel(label, CredentialType.Totp); + + Assert.Equal(CredentialPeriod.Period30, period); + Assert.Equal("Microsoft:demo", issuer); + Assert.Equal("test@outlook.com", account); } [Fact] public void CredentialParseLabel_TotpTypeAndNoDefaultPeriod_ReturnsCorrectlyParsedLabel() { - var label = "60/Microsoft:demo:test@outlook.com"; - var parsedLabel = Credential.ParseLabel(label, CredentialType.Totp); + string? label = "60/Microsoft:demo:test@outlook.com"; + (CredentialPeriod period, string? issuer, string account) = Credential.ParseLabel(label, CredentialType.Totp); - Assert.Equal(CredentialPeriod.Period60, parsedLabel.period); - Assert.Equal("Microsoft:demo", parsedLabel.issuer); - Assert.Equal("test@outlook.com", parsedLabel.account); + Assert.Equal(CredentialPeriod.Period60, period); + Assert.Equal("Microsoft:demo", issuer); + Assert.Equal("test@outlook.com", account); } [Fact] public void CredentialParseLabel_HotpType_ReturnsCorrectlyParsedLabel() { - var label = "60/Microsoft:demo:test@outlook.com"; - var parsedLabel = Credential.ParseLabel(label, CredentialType.Hotp); + string? label = "60/Microsoft:demo:test@outlook.com"; + (CredentialPeriod period, string? issuer, string account) = Credential.ParseLabel(label, CredentialType.Hotp); - Assert.Equal(CredentialPeriod.Undefined, parsedLabel.period); - Assert.Equal("60/Microsoft:demo", parsedLabel.issuer); - Assert.Equal("test@outlook.com", parsedLabel.account); + Assert.Equal(CredentialPeriod.Undefined, period); + Assert.Equal("60/Microsoft:demo", issuer); + Assert.Equal("test@outlook.com", account); } [Fact] public void CredentialParseLabel_HotpType_ReturnsCorrectlyParsedLabel_2() { - var label = "Microsoft:test@outlook.com"; - var parsedLabel = Credential.ParseLabel(label, CredentialType.Hotp); + string? label = "Microsoft:test@outlook.com"; + (CredentialPeriod period, string? issuer, string account) = Credential.ParseLabel(label, CredentialType.Hotp); - Assert.Equal(CredentialPeriod.Undefined, parsedLabel.period); - Assert.Equal("Microsoft", parsedLabel.issuer); - Assert.Equal("test@outlook.com", parsedLabel.account); + Assert.Equal(CredentialPeriod.Undefined, period); + Assert.Equal("Microsoft", issuer); + Assert.Equal("test@outlook.com", account); } [Fact] public void CredentialParseLabel_Totp15sAccount_ReturnsCorrectlyParsedLabel() { - var label = "15/test@outlook.com"; - var parsedLabel = Credential.ParseLabel(label, CredentialType.Totp); + string? label = "15/test@outlook.com"; + (CredentialPeriod period, string? issuer, string account) = Credential.ParseLabel(label, CredentialType.Totp); - Assert.Equal(CredentialPeriod.Period15, parsedLabel.period); - Assert.Null(parsedLabel.issuer); - Assert.Equal("test@outlook.com", parsedLabel.account); + Assert.Equal(CredentialPeriod.Period15, period); + Assert.Null(issuer); + Assert.Equal("test@outlook.com", account); } [Fact] public void CredentialParseLabel_Totp30sAccount_ReturnsCorrectlyParsedLabel() { - var label = "test@outlook.com"; - var parsedLabel = Credential.ParseLabel(label, CredentialType.Totp); + string? label = "test@outlook.com"; + (CredentialPeriod period, string? issuer, string account) = Credential.ParseLabel(label, CredentialType.Totp); - Assert.Equal(CredentialPeriod.Period30, parsedLabel.period); - Assert.Null(parsedLabel.issuer); - Assert.Equal("test@outlook.com", parsedLabel.account); + Assert.Equal(CredentialPeriod.Period30, period); + Assert.Null(issuer); + Assert.Equal("test@outlook.com", account); } [Fact] public void CredentialParseLabel_HotpAccount_ReturnsCorrectlyParsedLabel() { - var label = "test@outlook.com"; - var parsedLabel = Credential.ParseLabel(label, CredentialType.Hotp); + string? label = "test@outlook.com"; + (CredentialPeriod period, string? issuer, string account) = Credential.ParseLabel(label, CredentialType.Hotp); - Assert.Equal(CredentialPeriod.Undefined, parsedLabel.period); - Assert.Null(parsedLabel.issuer); - Assert.Equal("test@outlook.com", parsedLabel.account); + Assert.Equal(CredentialPeriod.Undefined, period); + Assert.Null(issuer); + Assert.Equal("test@outlook.com", account); } [Theory] @@ -456,7 +477,7 @@ public void CredentialParseLabel_HotpAccount_ReturnsCorrectlyParsedLabel() [InlineData(CredentialType.Hotp, CredentialPeriod.Undefined, null, "1234567890123456789012345678901234567890123456789012345678901234", "1234567890123456789012345678901234567890123456789012345678901234")] public void CredentialParseLabel_TotalLength64_ReturnsCorrectlyParsedLabel(CredentialType type, CredentialPeriod period, string? issuer, string account, string label) { - var parsedLabel = Credential.ParseLabel(label, type); + (CredentialPeriod period, string? issuer, string account) parsedLabel = Credential.ParseLabel(label, type); Assert.Equal(period, parsedLabel.period); Assert.Equal(issuer, parsedLabel.issuer); diff --git a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Otp/Commands/ConfigureSlotCommandTests.cs b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Otp/Commands/ConfigureSlotCommandTests.cs index 7e57befa..2d9f5f1c 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Otp/Commands/ConfigureSlotCommandTests.cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Otp/Commands/ConfigureSlotCommandTests.cs @@ -296,7 +296,7 @@ public void CreateCommandApdu_GetP1Property_ReturnsCorrectValueForSlot(Slot otpS [Fact] public void CreateCommandApdu_GetP2Property_ReturnsZero() { - var command =new ConfigureSlotCommand(); + var command = new ConfigureSlotCommand(); byte p2 = command.CreateCommandApdu().P2; @@ -325,7 +325,7 @@ public void CreateCommandApdu_ExtendedFlags_PlacedCorrectlyInDataBuffer() ReadOnlyMemory data = command.CreateCommandApdu().Data; byte dataSlice = data.Slice(ConfigureSlotCommand.FixedDataLength + ConfigureSlotCommand.UidLength - + ConfigureSlotCommand.AesKeyLength + + ConfigureSlotCommand.AesKeyLength + ConfigureSlotCommand.AccessCodeLength + 1).Span[0]; @@ -379,9 +379,9 @@ public void CreateCommandApdu_ReservedSection_IsAlwaysZeroInBuffer() ReadOnlyMemory data = command.CreateCommandApdu().Data; ReadOnlySpan dataSlice = data.Slice(ConfigureSlotCommand.FixedDataLength - + ConfigureSlotCommand.UidLength - + ConfigureSlotCommand.AesKeyLength - + ConfigureSlotCommand.AccessCodeLength + + ConfigureSlotCommand.UidLength + + ConfigureSlotCommand.AesKeyLength + + ConfigureSlotCommand.AccessCodeLength + 4, 2).Span; short actualReserved = BinaryPrimitives.ReadInt16LittleEndian(dataSlice); diff --git a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Otp/Commands/GetDeviceInfoCommandTests.cs b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Otp/Commands/GetDeviceInfoCommandTests.cs index c371df5c..410b7372 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Otp/Commands/GetDeviceInfoCommandTests.cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Otp/Commands/GetDeviceInfoCommandTests.cs @@ -98,7 +98,7 @@ public void CreateResponseApdu_ReturnsCorrectType() var command = new GetDeviceInfoCommand(); // Act - var response = command.CreateResponseForApdu(responseApdu); + GetDeviceInfoResponse? response = command.CreateResponseForApdu(responseApdu); // Assert Assert.True(response is GetDeviceInfoResponse); diff --git a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Otp/Commands/UpdateSlotCommandTests.cs b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Otp/Commands/UpdateSlotCommandTests.cs index 2176838c..0a142a8d 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Otp/Commands/UpdateSlotCommandTests.cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Otp/Commands/UpdateSlotCommandTests.cs @@ -215,7 +215,7 @@ public void CreateCommandApdu_ExtendedFlags_PlacedCorrectlyInDataBuffer() + UpdateSlotCommand.AesKeyLength + UpdateSlotCommand.AccessCodeLength + 1).Span[0]; - + Assert.Equal(expectedFlags, (ExtendedFlags)dataSlice); } @@ -251,7 +251,7 @@ public void CreateCommandApdu_ConfigurationFlags_PlacedCorrectlyInDataBuffer() + UpdateSlotCommand.AesKeyLength + UpdateSlotCommand.AccessCodeLength + 3).Span[0]; - + Assert.Equal(expectedFlags, (ConfigurationFlags)dataSlice); } @@ -267,10 +267,10 @@ public void CreateCommandApdu_FlagsSet_AllPrecedingBytesZero() ReadOnlyMemory data = command.CreateCommandApdu().Data; - Assert.DoesNotContain(data.ToArray().Take(UpdateSlotCommand.FixedDataLength - + UpdateSlotCommand.UidLength - + UpdateSlotCommand.AesKeyLength - + UpdateSlotCommand.AccessCodeLength + Assert.DoesNotContain(data.ToArray().Take(UpdateSlotCommand.FixedDataLength + + UpdateSlotCommand.UidLength + + UpdateSlotCommand.AesKeyLength + + UpdateSlotCommand.AccessCodeLength + 1), currentByte => currentByte != 0); } diff --git a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Otp/NdefDataReaderTests.cs b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Otp/NdefDataReaderTests.cs index 0bc4233e..4a541770 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Otp/NdefDataReaderTests.cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Otp/NdefDataReaderTests.cs @@ -268,7 +268,7 @@ public void ToUri_GivenUnsupportedPrefix_ThrowsInvalidOperationException() [InlineData(18, "rtsp://", "/")] [InlineData(19, "urn:", "")] [InlineData(20, "pop:", "")] - [InlineData(21, "sip:" ,"")] + [InlineData(21, "sip:", "")] [InlineData(22, "sips:", "")] [InlineData(23, "tftp:", "")] [InlineData(24, "btspp://", "/")] diff --git a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Otp/Operations/ConfigureYubicoOtpTests.cs b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Otp/Operations/ConfigureYubicoOtpTests.cs index 681371b5..3e41d7ec 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Otp/Operations/ConfigureYubicoOtpTests.cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Otp/Operations/ConfigureYubicoOtpTests.cs @@ -43,7 +43,7 @@ public void TestNoSlot() [Fact] public void TestGeneratedAndSpecifiedKey() { - _ = _op.GenerateKey(new byte[ConfigureYubicoOtp.KeySize]); + _ = _op.GenerateKey(new byte[ConfigureYubicoOtp.KeySize]); InvalidOperationException ex = Assert.Throws(() => _op.UseKey(_validKey)); Assert.Equal(ExceptionMessages.CantSpecifyKeyAndGenerate, ex.Message); diff --git a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Pipelines/CommandChainingTransformTests.cs b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Pipelines/CommandChainingTransformTests.cs index dc9662f8..53acf898 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Pipelines/CommandChainingTransformTests.cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Pipelines/CommandChainingTransformTests.cs @@ -12,11 +12,11 @@ // See the License for the specific language governing permissions and // limitations under the License. -using Microsoft.VisualStudio.TestPlatform.ObjectModel.Client; -using Moq; using System; using System.Collections.Generic; using System.Linq; +using Microsoft.VisualStudio.TestPlatform.ObjectModel.Client; +using Moq; using Xunit; using Yubico.Core.Iso7816; diff --git a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Pipelines/OathResponseChainingTransformTests.cs b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Pipelines/OathResponseChainingTransformTests.cs index 3fa09745..224e435a 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Pipelines/OathResponseChainingTransformTests.cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Pipelines/OathResponseChainingTransformTests.cs @@ -12,8 +12,8 @@ // See the License for the specific language governing permissions and // limitations under the License. -using Moq; using System; +using Moq; using Xunit; using Yubico.Core.Iso7816; diff --git a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Pipelines/ResponseChainingTransformTests.cs b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Pipelines/ResponseChainingTransformTests.cs index 4405893c..b91c3f99 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Pipelines/ResponseChainingTransformTests.cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Pipelines/ResponseChainingTransformTests.cs @@ -12,8 +12,8 @@ // See the License for the specific language governing permissions and // limitations under the License. -using Moq; using System; +using Moq; using Xunit; using Yubico.Core.Iso7816; diff --git a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Pipelines/Scp03ApduTransformTests.cs b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Pipelines/Scp03ApduTransformTests.cs index d1a55354..287cf013 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Pipelines/Scp03ApduTransformTests.cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Pipelines/Scp03ApduTransformTests.cs @@ -16,11 +16,11 @@ using System.Linq; using System.Security.Cryptography; using Xunit; +using Yubico.Core.Buffers; +using Yubico.Core.Iso7816; using Yubico.YubiKey.InterIndustry.Commands; using Yubico.YubiKey.Piv.Commands; using Yubico.YubiKey.Scp03; -using Yubico.Core.Iso7816; -using Yubico.Core.Buffers; namespace Yubico.YubiKey.Pipelines { diff --git a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Pipelines/SmartCardTransformTests.cs b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Pipelines/SmartCardTransformTests.cs index ef1c0420..f76f1e66 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Pipelines/SmartCardTransformTests.cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Pipelines/SmartCardTransformTests.cs @@ -12,8 +12,8 @@ // See the License for the specific language governing permissions and // limitations under the License. -using Moq; using System; +using Moq; using Xunit; using Yubico.Core.Devices.SmartCard; using Yubico.Core.Iso7816; diff --git a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/Commands/ChangeRefCommandTests.cs b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/Commands/ChangeRefCommandTests.cs index 46311132..b06d88ce 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/Commands/ChangeRefCommandTests.cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/Commands/ChangeRefCommandTests.cs @@ -217,7 +217,7 @@ public void Constructor_BadPin_CorrectException(int pinLength, byte slotNum) public void Constructor_NullCurrentPin_CorrectException() { byte[] pin = GetPinArray(6, 0); - _ = Assert.Throws(() => new ChangeReferenceDataCommand(0x80, null, pin)); + _ = Assert.Throws(() => new ChangeReferenceDataCommand(0x80, null, pin)); } [Fact] diff --git a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/Commands/CompleteAuthMgmtKeyCommandTests.cs b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/Commands/CompleteAuthMgmtKeyCommandTests.cs index f9cd6d21..17387355 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/Commands/CompleteAuthMgmtKeyCommandTests.cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/Commands/CompleteAuthMgmtKeyCommandTests.cs @@ -67,7 +67,8 @@ public void Mutual_CreateResponse_CorrectType() { byte successSw1 = unchecked((byte)(SWConstants.Success >> 8)); byte successSw2 = unchecked((byte)SWConstants.Success); - byte[] apduMutual = new byte[] { + byte[] apduMutual = new byte[] + { 0x7C, 0x0A, 0x82, 0x08, 0xAC, 0x29, 0xA4, 0x5E, 0x1F, 0x42, 0x8A, 0x23, successSw1, successSw2 }; @@ -196,7 +197,9 @@ public void CreateCommandApdu_GetNe_ReturnsZero(bool isMutual) public void CreateCommandApduSingle_GetData_ReturnsCorrect() { var expected = new List( - new byte[12] { 0x7C, 0x0A, 0x82, 0x08, 0x54, 0xFE, 0xAA, 0x17, 0xAC, 0x05, 0x02, 0x36 + new byte[12] + { + 0x7C, 0x0A, 0x82, 0x08, 0x54, 0xFE, 0xAA, 0x17, 0xAC, 0x05, 0x02, 0x36 }); CommandApdu cmdApdu = GetCommandApdu(false, true); @@ -212,10 +215,12 @@ public void CreateCommandApduSingle_GetData_ReturnsCorrect() public void CreateCommandApduMutual_GetData_ReturnsCorrect() { var expected = new List( - new byte[24] { + new byte[24] + { 0x7C, 0x16, 0x80, 0x08, 0xD0, 0xFE, 0x1A, 0x35, 0xA4, 0xE9, 0x40, 0xF8, - 0x81, 0x08, 0xAC, 0x29, 0xA4, 0x5E, 0x1F, 0x42, 0x8A, 0x23, 0x82, 0x00 } - ); + 0x81, 0x08, 0xAC, 0x29, 0xA4, 0x5E, 0x1F, 0x42, 0x8A, 0x23, 0x82, 0x00 + } + ); CommandApdu cmdApdu = GetCommandApdu(true, true); @@ -243,10 +248,11 @@ private static CompleteAuthenticateManagementKeyCommand GetCommandObject(bool is try { - if (isRandomFixed == true) + if (isRandomFixed) { replacement = RandomObjectUtility.SetRandomProviderFixedBytes(GetFixedBytes()); } + return new CompleteAuthenticateManagementKeyCommand(response, mgmtKey); } finally @@ -266,7 +272,8 @@ private static byte[] GetFixedBytes() // Currently, setting to 256 seems to prevent problems when the // threading race goes bad (this is because the maximum block size of // an RSA encryption/signature is 256). - return new byte[256] { + return new byte[256] + { 0xA4, 0xC4, 0xD9, 0x23, 0x74, 0x59, 0x7F, 0x64, 0xA6, 0xD3, 0xCB, 0x2C, 0x10, 0xF0, 0xCD, 0x2D, 0x57, 0xE9, 0x9F, 0x58, 0xC8, 0x57, 0x10, 0x6E, @@ -314,13 +321,14 @@ private static InitializeAuthenticateManagementKeyResponse GetInitResponse(bool byte sw1 = unchecked((byte)(SWConstants.Success >> 8)); byte sw2 = unchecked((byte)SWConstants.Success); byte tag1 = 0x81; - if (isMutualAuth == true) + if (isMutualAuth) { tag1 = 0x80; } var responseApdu = new ResponseApdu( - new byte[] { + new byte[] + { 0x7C, 0x0A, tag1, 0x08, 0x39, 0xA0, 0xA8, 0xE9, 0xF5, 0x28, 0x87, 0x75, sw1, sw2 }); diff --git a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/Commands/CompleteAuthMgmtKeyResponseTests.cs b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/Commands/CompleteAuthMgmtKeyResponseTests.cs index f4559f96..0098ed32 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/Commands/CompleteAuthMgmtKeyResponseTests.cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/Commands/CompleteAuthMgmtKeyResponseTests.cs @@ -47,7 +47,7 @@ public void Constructor_NullResponseApdu_ThrowsException() [InlineData(ApduError, ResponseStatus.Failed)] public void ConstructorSingle_ResponseApdu_SetsStatusCorrectly(int responseFlag, ResponseStatus status) { - var responseApdu = GetResponseApdu(responseFlag); + ResponseApdu? responseApdu = GetResponseApdu(responseFlag); var response = new CompleteAuthenticateManagementKeyResponse(responseApdu, _empty); Assert.Equal(status, response.Status); @@ -59,7 +59,7 @@ public void ConstructorSingle_ResponseApdu_SetsStatusCorrectly(int responseFlag, [InlineData(ApduError, ResponseStatus.Failed)] public void ConstructorMutual_ResponseApdu_SetsStatusCorrectly(int responseFlag, ResponseStatus status) { - var responseApdu = GetResponseApdu(responseFlag); + ResponseApdu? responseApdu = GetResponseApdu(responseFlag); var response = new CompleteAuthenticateManagementKeyResponse(responseApdu, _yubiKeyAuthenticationExpectedResponse); Assert.Equal(status, response.Status); @@ -71,7 +71,7 @@ public void ConstructorMutual_ResponseApdu_SetsStatusCorrectly(int responseFlag, [InlineData(ApduError, SWConstants.FunctionNotSupported)] public void ConstructorSingle_ResponseApdu_SetsStatusWordCorrectly(int responseFlag, short statusWord) { - var responseApdu = GetResponseApdu(responseFlag); + ResponseApdu? responseApdu = GetResponseApdu(responseFlag); var response = new CompleteAuthenticateManagementKeyResponse(responseApdu, _empty); Assert.Equal(statusWord, response.StatusWord); @@ -83,7 +83,7 @@ public void ConstructorSingle_ResponseApdu_SetsStatusWordCorrectly(int responseF [InlineData(ApduError, SWConstants.FunctionNotSupported)] public void ConstructorMutual_ResponseApdu_SetsStatusWordCorrectly(int responseFlag, short statusWord) { - var responseApdu = GetResponseApdu(responseFlag); + ResponseApdu? responseApdu = GetResponseApdu(responseFlag); var response = new CompleteAuthenticateManagementKeyResponse(responseApdu, _yubiKeyAuthenticationExpectedResponse); Assert.Equal(statusWord, response.StatusWord); @@ -92,7 +92,7 @@ public void ConstructorMutual_ResponseApdu_SetsStatusWordCorrectly(int responseF [Fact] public void ErrorInput_GetData_ThrowException() { - var responseApdu = GetResponseApdu(ApduError); + ResponseApdu? responseApdu = GetResponseApdu(ApduError); var response = new CompleteAuthenticateManagementKeyResponse(responseApdu, _yubiKeyAuthenticationExpectedResponse); _ = Assert.Throws(() => response.GetData()); @@ -101,7 +101,7 @@ public void ErrorInput_GetData_ThrowException() [Fact] public void ConstructorSingle_GetDataNonEmptyYubiKeyAuthenticationResponse_ThrowsException() { - var responseApdu = GetResponseApdu(ApduSingle); + ResponseApdu? responseApdu = GetResponseApdu(ApduSingle); var response = new CompleteAuthenticateManagementKeyResponse(responseApdu, _yubiKeyAuthenticationExpectedResponse); _ = Assert.Throws(() => response.GetData()); @@ -114,7 +114,7 @@ public void ConstructorMutual_GetData_CorrectResult( int responseFlag, AuthenticateManagementKeyResult expectedAuth) { - var responseApdu = GetResponseApdu(responseFlag); + ResponseApdu? responseApdu = GetResponseApdu(responseFlag); var response = new CompleteAuthenticateManagementKeyResponse(responseApdu, _yubiKeyAuthenticationExpectedResponse); AuthenticateManagementKeyResult getData = response.GetData(); @@ -127,7 +127,7 @@ public void ConstructorMutual_GetData_CorrectResult( [InlineData(ApduNoAuth, AuthenticateManagementKeyResult.SingleAuthenticationFailed)] public void ConstructorSingle_GetData_CorrectResult(int responseFlag, AuthenticateManagementKeyResult expectedAuth) { - var responseApdu = GetResponseApdu(responseFlag); + ResponseApdu? responseApdu = GetResponseApdu(responseFlag); var response = new CompleteAuthenticateManagementKeyResponse(responseApdu, _empty); AuthenticateManagementKeyResult getData = response.GetData(); @@ -138,7 +138,7 @@ public void ConstructorSingle_GetData_CorrectResult(int responseFlag, Authentica [Fact] public void YubiKeyFailAuth_GetData_CorrectResult() { - var responseApdu = GetResponseApdu(ApduMutual); + ResponseApdu? responseApdu = GetResponseApdu(ApduMutual); var response = new CompleteAuthenticateManagementKeyResponse(responseApdu, _wrongYubiKeyAuthenticationResponse); AuthenticateManagementKeyResult getData = response.GetData(); diff --git a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/Commands/GenPairCommandTests.cs b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/Commands/GenPairCommandTests.cs index 54c3c6b3..8b5f8014 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/Commands/GenPairCommandTests.cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/Commands/GenPairCommandTests.cs @@ -248,7 +248,7 @@ public void CreateCommandApdu_GetData_ReturnsCorrectPrefix(int cStyle) return; } - bool compareResult = (data.Span[0] == 0xAC) && (data.Span[1] == 0x03) && (data.Span[2] == 0x80) && (data.Span[3] == 0x01); + bool compareResult = data.Span[0] == 0xAC && data.Span[1] == 0x03 && data.Span[2] == 0x80 && data.Span[3] == 0x01; Assert.True(compareResult); } @@ -291,7 +291,7 @@ public void CreateCommandApdu_GetData_ReturnsCorrectPinPolicy(int cStyle, PivPin return; } - bool compareResult = (data.Span[5] == 0xAA) && (data.Span[6] == 0x01) && (data.Span[7] == (byte)pinPolicy); + bool compareResult = data.Span[5] == 0xAA && data.Span[6] == 0x01 && data.Span[7] == (byte)pinPolicy; Assert.True(compareResult); } @@ -334,7 +334,7 @@ public void CreateCommandApdu_GetData_ReturnsCorrectTouchPolicy(int cStyle, PivT return; } - bool compareResult = (data.Span[8] == 0xAB) && (data.Span[9] == 0x01) && (data.Span[10] == (byte)touchPolicy); + bool compareResult = data.Span[8] == 0xAB && data.Span[9] == 0x01 && data.Span[10] == (byte)touchPolicy; Assert.True(compareResult); } diff --git a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/Commands/ImportKeyCommandTests.cs b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/Commands/ImportKeyCommandTests.cs index 07bb1cb0..aefc0602 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/Commands/ImportKeyCommandTests.cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/Commands/ImportKeyCommandTests.cs @@ -386,11 +386,11 @@ public void CreateCommandApdu_GetData_ReturnsPolicy( byte[] pinData = new byte[] { 0xAA, 0x01, (byte)pinPolicy }; byte[] touchData = new byte[] { 0xAB, 0x01, (byte)touchPolicy }; var expected = new List(keyData.EncodedPrivateKey.ToArray()); - if ((pinPolicy != PivPinPolicy.None) && (pinPolicy != PivPinPolicy.Default)) + if (pinPolicy != PivPinPolicy.None && pinPolicy != PivPinPolicy.Default) { expected.AddRange(pinData); } - if ((touchPolicy != PivTouchPolicy.None) && (touchPolicy != PivTouchPolicy.Default)) + if (touchPolicy != PivTouchPolicy.None && touchPolicy != PivTouchPolicy.Default) { expected.AddRange(touchData); } diff --git a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/Commands/InitAuthMgmtKeyResponseTests.cs b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/Commands/InitAuthMgmtKeyResponseTests.cs index 8aebdb9e..15b9e7fd 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/Commands/InitAuthMgmtKeyResponseTests.cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/Commands/InitAuthMgmtKeyResponseTests.cs @@ -36,9 +36,10 @@ public void Constructor_InvalidLength_CorrectException() byte sw1 = unchecked((byte)(SWConstants.Success >> 8)); byte sw2 = unchecked((byte)SWConstants.Success); var responseApdu = new ResponseApdu( - new byte[] { 0x7C, 0x09, 0x81, 0x07, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, sw1, sw2 }); + new byte[] { 0x7C, 0x09, 0x81, 0x07, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, sw1, sw2 }); - _ = Assert.Throws(() => new InitializeAuthenticateManagementKeyResponse(responseApdu)); + _ = Assert.Throws(() => + new InitializeAuthenticateManagementKeyResponse(responseApdu)); } [Fact] @@ -47,9 +48,10 @@ public void Constructor_InvalidT0_CorrectException() byte sw1 = unchecked((byte)(SWConstants.Success >> 8)); byte sw2 = unchecked((byte)SWConstants.Success); var responseApdu = new ResponseApdu( - new byte[] { 0x78, 0x0A, 0x81, 0x08, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, sw1, sw2 }); + new byte[] { 0x78, 0x0A, 0x81, 0x08, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, sw1, sw2 }); - _ = Assert.Throws(() => new InitializeAuthenticateManagementKeyResponse(responseApdu)); + _ = Assert.Throws(() => + new InitializeAuthenticateManagementKeyResponse(responseApdu)); } [Fact] @@ -58,9 +60,10 @@ public void Constructor_InvalidT2_CorrectException() byte sw1 = unchecked((byte)(SWConstants.Success >> 8)); byte sw2 = unchecked((byte)SWConstants.Success); var responseApdu = new ResponseApdu( - new byte[] { 0x7C, 0x0A, 0x82, 0x08, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, sw1, sw2 }); + new byte[] { 0x7C, 0x0A, 0x82, 0x08, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, sw1, sw2 }); - _ = Assert.Throws(() => new InitializeAuthenticateManagementKeyResponse(responseApdu)); + _ = Assert.Throws(() => + new InitializeAuthenticateManagementKeyResponse(responseApdu)); } [Fact] @@ -69,9 +72,10 @@ public void Constructor_InvalidL1_CorrectException() byte sw1 = unchecked((byte)(SWConstants.Success >> 8)); byte sw2 = unchecked((byte)SWConstants.Success); var responseApdu = new ResponseApdu( - new byte[] { 0x7C, 0x0A, 0x81, 0x07, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, sw1, sw2 }); + new byte[] { 0x7C, 0x0A, 0x81, 0x07, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, sw1, sw2 }); - _ = Assert.Throws(() => new InitializeAuthenticateManagementKeyResponse(responseApdu)); + _ = Assert.Throws(() => + new InitializeAuthenticateManagementKeyResponse(responseApdu)); } [Fact] @@ -80,7 +84,7 @@ public void Constructor_SuccessResponseApdu_SetsStatusWordCorrectly() byte sw1 = unchecked((byte)(SWConstants.Success >> 8)); byte sw2 = unchecked((byte)SWConstants.Success); var responseApdu = new ResponseApdu( - new byte[] { 0x7C, 0x0A, 0x81, 0x08, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, sw1, sw2 }); + new byte[] { 0x7C, 0x0A, 0x81, 0x08, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, sw1, sw2 }); var response = new InitializeAuthenticateManagementKeyResponse(responseApdu); @@ -93,7 +97,7 @@ public void Constructor_SuccessResponseApdu_SetsStatusCorrectly() byte sw1 = unchecked((byte)(SWConstants.Success >> 8)); byte sw2 = unchecked((byte)SWConstants.Success); var responseApdu = new ResponseApdu( - new byte[] { 0x7C, 0x0A, 0x81, 0x08, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, sw1, sw2 }); + new byte[] { 0x7C, 0x0A, 0x81, 0x08, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, sw1, sw2 }); var response = new InitializeAuthenticateManagementKeyResponse(responseApdu); @@ -108,13 +112,13 @@ public void Constructor_SuccessResponseApdu_GetDataCorrectBool(bool isMutual) byte sw1 = unchecked((byte)(SWConstants.Success >> 8)); byte sw2 = unchecked((byte)SWConstants.Success); byte tag2 = 0x81; - if (isMutual == true) + if (isMutual) { tag2 = 0x80; } var responseApdu = new ResponseApdu( - new byte[] { 0x7C, 0x0A, tag2, 0x08, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, sw1, sw2 }); + new byte[] { 0x7C, 0x0A, tag2, 0x08, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, sw1, sw2 }); var response = new InitializeAuthenticateManagementKeyResponse(responseApdu); @@ -132,7 +136,7 @@ public void Constructor_SuccessResponseApdu_GetDataCorrectBytes() var expected = new List( new byte[8] { 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88 }); var responseApdu = new ResponseApdu( - new byte[] { 0x7C, 0x0A, 0x81, 0x08, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, sw1, sw2 }); + new byte[] { 0x7C, 0x0A, 0x81, 0x08, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, sw1, sw2 }); var response = new InitializeAuthenticateManagementKeyResponse(responseApdu); diff --git a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/Commands/PivCommandResponseTestData.cs b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/Commands/PivCommandResponseTestData.cs index dd44496b..86b99b3c 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/Commands/PivCommandResponseTestData.cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/Commands/PivCommandResponseTestData.cs @@ -14,8 +14,8 @@ using System.Collections.Generic; using System.Security.Cryptography; -using Yubico.YubiKey.TestUtilities; using Yubico.Core.Tlv; +using Yubico.YubiKey.TestUtilities; namespace Yubico.YubiKey.Piv.Commands { @@ -318,7 +318,7 @@ private static byte[] BuildPutDataEncoding(int[] format, bool isCorrect, int ind valueLen++; } } - if ((format[index] == 0xFE) && (isCorrect == false)) + if (format[index] == 0xFE && isCorrect == false) { valueLen = 1; } diff --git a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/Commands/PutDataCommandTests.cs b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/Commands/PutDataCommandTests.cs index ded001be..8ddbdec7 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/Commands/PutDataCommandTests.cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/Commands/PutDataCommandTests.cs @@ -62,9 +62,10 @@ public void Constructor_Application_Piv(int constructorToUse) [Fact] public void SetProperties_Old_MatchesNew() { - var command = new PutDataCommand(); - - command.DataTag = (int)PivDataTag.Capability; + var command = new PutDataCommand + { + DataTag = (int)PivDataTag.Capability + }; #pragma warning disable CS0618 // Testing an obsolete feature Assert.Equal(PivDataTag.Capability, command.Tag); @@ -74,10 +75,11 @@ public void SetProperties_Old_MatchesNew() [Fact] public void SetProperties_New_MatchesOld() { - var command = new PutDataCommand(); - + var command = new PutDataCommand + { #pragma warning disable CS0618 // Testing an obsolete feature - command.Tag = PivDataTag.SecurityObject; + Tag = PivDataTag.SecurityObject + }; #pragma warning restore CS0618 Assert.Equal((int)PivDataTag.SecurityObject, command.DataTag); diff --git a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/Commands/SetPinRetriesCommandTests.cs b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/Commands/SetPinRetriesCommandTests.cs index f089380c..015b4e6e 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/Commands/SetPinRetriesCommandTests.cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/Commands/SetPinRetriesCommandTests.cs @@ -211,7 +211,7 @@ public void Constructor_BadCount_CorrectException(byte pinCount, byte pukCount) private static CommandApdu GetPinRetriesCommandApdu(int cStyle, byte pinRetries, byte pukRetries) { - SetPinRetriesCommand command = GetCommandObject (cStyle, pinRetries, pukRetries); + SetPinRetriesCommand command = GetCommandObject(cStyle, pinRetries, pukRetries); CommandApdu returnValue = command.CreateCommandApdu(); return returnValue; diff --git a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/Commands/SetPinRetriesResponseTests.cs b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/Commands/SetPinRetriesResponseTests.cs index 26607b8b..b7946ffc 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/Commands/SetPinRetriesResponseTests.cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/Commands/SetPinRetriesResponseTests.cs @@ -55,25 +55,25 @@ public void Constructor_SuccessResponseApdu_SetsStatusCorrectly() [Fact] public void Constructor_AuthReqdResponseApdu_SetsStatusCorrectly() { - byte sw1 = unchecked((byte)(SWConstants.SecurityStatusNotSatisfied >> 8)); - byte sw2 = unchecked((byte)SWConstants.SecurityStatusNotSatisfied); - var responseApdu = new ResponseApdu(new byte[] { sw1, sw2 }); + byte sw1 = unchecked((byte)(SWConstants.SecurityStatusNotSatisfied >> 8)); + byte sw2 = unchecked((byte)SWConstants.SecurityStatusNotSatisfied); + var responseApdu = new ResponseApdu(new byte[] { sw1, sw2 }); - var setPinRetriesResponse = new SetPinRetriesResponse(responseApdu); + var setPinRetriesResponse = new SetPinRetriesResponse(responseApdu); - Assert.Equal(ResponseStatus.AuthenticationRequired, setPinRetriesResponse.Status); + Assert.Equal(ResponseStatus.AuthenticationRequired, setPinRetriesResponse.Status); } [Fact] public void Constructor_ErrorResponseApdu_SetsStatusCorrectly() { - byte sw1 = unchecked((byte)(SWConstants.FunctionNotSupported >> 8)); - byte sw2 = unchecked((byte)SWConstants.FunctionNotSupported); - var responseApdu = new ResponseApdu(new byte[] { sw1, sw2 }); + byte sw1 = unchecked((byte)(SWConstants.FunctionNotSupported >> 8)); + byte sw2 = unchecked((byte)SWConstants.FunctionNotSupported); + var responseApdu = new ResponseApdu(new byte[] { sw1, sw2 }); - var setPinRetriesResponse = new SetPinRetriesResponse(responseApdu); + var setPinRetriesResponse = new SetPinRetriesResponse(responseApdu); - Assert.Equal(ResponseStatus.Failed, setPinRetriesResponse.Status); + Assert.Equal(ResponseStatus.Failed, setPinRetriesResponse.Status); } } } diff --git a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/Commands/TripleDesTests.cs b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/Commands/TripleDesTests.cs index 5db2672d..677d31cf 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/Commands/TripleDesTests.cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/Commands/TripleDesTests.cs @@ -334,7 +334,7 @@ private static int GetNextVector( // no bytes placed into the buffer. private static int GetNextKeyData(byte[] keyData, int nextIndex) { - if ((nextIndex < 0) || (nextIndex > 255)) + if (nextIndex < 0 || nextIndex > 255) { return -1; } diff --git a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/Commands/VersionCommandTests.cs b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/Commands/VersionCommandTests.cs index cd484dc6..2894c464 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/Commands/VersionCommandTests.cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/Commands/VersionCommandTests.cs @@ -87,7 +87,7 @@ public void CreateResponseForApdu_ReturnsCorrectType() var versionCommand = new VersionCommand(); // Act - var versionResponse = versionCommand.CreateResponseForApdu(responseApdu); + VersionResponse? versionResponse = versionCommand.CreateResponseForApdu(responseApdu); // Assert Assert.True(versionResponse is VersionResponse); diff --git a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/KeyTests.cs b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/KeyTests.cs index aa999dc3..3ad5f2d0 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/KeyTests.cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/KeyTests.cs @@ -13,8 +13,8 @@ // limitations under the License. using System.Security.Cryptography; -using Yubico.YubiKey.Cryptography; using Xunit; +using Yubico.YubiKey.Cryptography; namespace Yubico.YubiKey.Piv { diff --git a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/Objects/AdminTests.cs b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/Objects/AdminTests.cs index 7b02f302..809b63a2 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/Objects/AdminTests.cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/Objects/AdminTests.cs @@ -14,8 +14,8 @@ using System; using System.Security.Cryptography; -using Yubico.YubiKey.TestUtilities; using Xunit; +using Yubico.YubiKey.TestUtilities; namespace Yubico.YubiKey.Piv.Objects { @@ -109,7 +109,7 @@ public void SetSalt_Correct() using var admin = new AdminData(); admin.SetSalt(fixedBytes); - Assert.NotNull(admin.Salt); + _ = Assert.NotNull(admin.Salt); if (!(admin.Salt is null)) { var salt = (ReadOnlyMemory)admin.Salt; @@ -144,7 +144,7 @@ public void SetSalt_ThenNull_Correct() using var admin = new AdminData(); admin.SetSalt(fixedBytes); - Assert.NotNull(admin.Salt); + _ = Assert.NotNull(admin.Salt); admin.SetSalt(ReadOnlyMemory.Empty); Assert.Null(admin.Salt); @@ -183,7 +183,7 @@ public void SetTime_Current_NotNull() using var admin = new AdminData(); admin.PinLastUpdated = DateTime.UtcNow; - Assert.NotNull(admin.PinLastUpdated); + _ = Assert.NotNull(admin.PinLastUpdated); } [Fact] @@ -365,7 +365,7 @@ public void FullDecode_DateCorrect() }); long unixTimeSeconds = ((long)encoding.Span[30] & 255) << 24; unixTimeSeconds += ((long)encoding.Span[29] & 255) << 16; - unixTimeSeconds += ((long)encoding.Span[28] & 255) << 8; + unixTimeSeconds += ((long)encoding.Span[28] & 255) << 8; unixTimeSeconds += (long)encoding.Span[27] & 255; var expectedOffset = DateTimeOffset.FromUnixTimeSeconds(unixTimeSeconds); DateTime expected = expectedOffset.UtcDateTime; diff --git a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/Objects/CccTests.cs b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/Objects/CccTests.cs index 0dce53cf..060e9d0e 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/Objects/CccTests.cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/Objects/CccTests.cs @@ -14,8 +14,8 @@ using System; using System.Security.Cryptography; -using Yubico.YubiKey.TestUtilities; using Xunit; +using Yubico.YubiKey.TestUtilities; namespace Yubico.YubiKey.Piv.Objects { diff --git a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/Objects/ChuidTests.cs b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/Objects/ChuidTests.cs index 8ea6ecdc..044621b6 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/Objects/ChuidTests.cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/Objects/ChuidTests.cs @@ -14,8 +14,8 @@ using System; using System.Security.Cryptography; -using Yubico.YubiKey.TestUtilities; using Xunit; +using Yubico.YubiKey.TestUtilities; namespace Yubico.YubiKey.Piv.Objects { diff --git a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/Objects/PinProtectedTests.cs b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/Objects/PinProtectedTests.cs index e85d8b53..181230f7 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/Objects/PinProtectedTests.cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/Objects/PinProtectedTests.cs @@ -13,8 +13,8 @@ // limitations under the License. using System; -using Yubico.YubiKey.TestUtilities; using Xunit; +using Yubico.YubiKey.TestUtilities; namespace Yubico.YubiKey.Piv.Objects { @@ -91,7 +91,7 @@ public void SetMgmtKey_DataSame() using var pinProtect = new PinProtectedData(); pinProtect.SetManagementKey(mgmtKey); - Assert.NotNull(pinProtect.ManagementKey); + _ = Assert.NotNull(pinProtect.ManagementKey); if (!(pinProtect.ManagementKey is null)) { var getData = (ReadOnlyMemory)pinProtect.ManagementKey; @@ -241,7 +241,7 @@ public void Decode_Full_MgmtKeyCorrect() using var pinProtect = new PinProtectedData(); pinProtect.Decode(encodedData); - Assert.NotNull(pinProtect.ManagementKey); + _ = Assert.NotNull(pinProtect.ManagementKey); if (!(pinProtect.ManagementKey is null)) { var getData = (ReadOnlyMemory)pinProtect.ManagementKey; diff --git a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/PivDataTagTests.cs b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/PivDataTagTests.cs index cecfe14c..af1910e8 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/PivDataTagTests.cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/PivDataTagTests.cs @@ -13,8 +13,8 @@ // limitations under the License. using System; -using Yubico.YubiKey.Piv.Commands; using Xunit; +using Yubico.YubiKey.Piv.Commands; namespace Yubico.YubiKey.Piv { diff --git a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/PivMetadataTests.cs b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/PivMetadataTests.cs index 87ebd554..22a9114f 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/PivMetadataTests.cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/PivMetadataTests.cs @@ -13,8 +13,8 @@ // limitations under the License. using System; -using Yubico.YubiKey.TestUtilities; using Xunit; +using Yubico.YubiKey.TestUtilities; namespace Yubico.YubiKey.Piv { @@ -198,7 +198,7 @@ public void Constructor_ValidInputPin_CorrectRetries() var pivMetadata = new PivMetadata(testData, PivSlot.Pin); Assert.True(pivMetadata.RetryCount == 4); - Assert.True(pivMetadata.RetriesRemaining== 5); + Assert.True(pivMetadata.RetriesRemaining == 5); } [Fact] diff --git a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/PivPrivateKeyTests.cs b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/PivPrivateKeyTests.cs index 78c0e804..a7100043 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/PivPrivateKeyTests.cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/PivPrivateKeyTests.cs @@ -13,8 +13,8 @@ // limitations under the License. using System; -using System.Security.Cryptography; using System.Linq; +using System.Security.Cryptography; using Xunit; namespace Yubico.YubiKey.Piv @@ -375,7 +375,7 @@ public void GetPivPrivateKey_FromPem(PivAlgorithm algorithm) private static int ReadTagLen(byte[] buffer, int offset, bool readValue) { // Make sure there are enough bytes to read. - if ((offset < 0) || (buffer.Length < offset + 2)) + if (offset < 0 || buffer.Length < offset + 2) { return -1; } @@ -388,7 +388,7 @@ private static int ReadTagLen(byte[] buffer, int offset, bool readValue) // beyond 83). This says the length is the next 1, 2, or 3 octets. int length = buffer[offset + 1]; int increment = 2; - if ((length == 0x80) || (length > 0x83)) + if (length == 0x80 || length > 0x83) { return -1; } @@ -449,7 +449,7 @@ private static Memory GetRsaComponent(PivAlgorithm algorithm, int tag) count = 128; } - if ((tag <= 0) || (tag > 5)) + if (tag <= 0 || tag > 5) { return Memory.Empty; } diff --git a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/PivPublicKeyTests.cs b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/PivPublicKeyTests.cs index b628b129..e14f1a62 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/PivPublicKeyTests.cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/PivPublicKeyTests.cs @@ -475,7 +475,7 @@ private static Memory GetCorrectMetadataEncoding(PivAlgorithm algorithm) 0x01, 0x00, 0x01 }), - PivAlgorithm.EccP256 => new Memory(new byte[] { + PivAlgorithm.EccP256 => new Memory(new byte[] { 0x7f, 0x49, 0x44, 0x86, 0x42, 0x04, 0x99, @@ -485,7 +485,7 @@ private static Memory GetCorrectMetadataEncoding(PivAlgorithm algorithm) 0xD1, 0x59, 0xDE, 0x66, 0x01, 0x0E, 0x3F, 0x21, 0x13, 0x29, 0xC5, 0x98, 0x56, 0x07, 0xB5, 0x26 }), - _ => new Memory(new byte[] { + _ => new Memory(new byte[] { 0x7f, 0x49, 0x64, 0x86, 0x62, 0x04, 0x99, diff --git a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/PivSessionAttestTests.cs b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/PivSessionAttestTests.cs index 75c0223a..88cfc075 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/PivSessionAttestTests.cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/PivSessionAttestTests.cs @@ -14,8 +14,8 @@ using System; using System.Security.Cryptography.X509Certificates; -using Yubico.YubiKey.TestUtilities; using Xunit; +using Yubico.YubiKey.TestUtilities; namespace Yubico.YubiKey.Piv { diff --git a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/PivSessionAuthTests.cs b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/PivSessionAuthTests.cs index e4b6a6b6..c15180d5 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/PivSessionAuthTests.cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/PivSessionAuthTests.cs @@ -13,9 +13,9 @@ // limitations under the License. using System; +using Xunit; using Yubico.YubiKey.Cryptography; using Yubico.YubiKey.TestUtilities; -using Xunit; namespace Yubico.YubiKey.Piv { diff --git a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/PivSessionCryptoTests.cs b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/PivSessionCryptoTests.cs index 3a9c9e74..71f44c87 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/PivSessionCryptoTests.cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/PivSessionCryptoTests.cs @@ -14,8 +14,8 @@ using System; using System.Security.Cryptography; -using Yubico.YubiKey.TestUtilities; using Xunit; +using Yubico.YubiKey.TestUtilities; namespace Yubico.YubiKey.Piv { diff --git a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/PivSessionKeyPairTests.cs b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/PivSessionKeyPairTests.cs index bff1531d..b57c49a6 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/PivSessionKeyPairTests.cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/PivSessionKeyPairTests.cs @@ -14,9 +14,9 @@ using System; using System.Security.Cryptography.X509Certificates; +using Xunit; using Yubico.YubiKey.Cryptography; using Yubico.YubiKey.TestUtilities; -using Xunit; namespace Yubico.YubiKey.Piv { diff --git a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/PivSessionMsrootsTests.cs b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/PivSessionMsrootsTests.cs index f1f29453..adb7cd89 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/PivSessionMsrootsTests.cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/PivSessionMsrootsTests.cs @@ -14,9 +14,9 @@ using System; using System.IO; +using Xunit; using Yubico.YubiKey.Cryptography; using Yubico.YubiKey.TestUtilities; -using Xunit; namespace Yubico.YubiKey.Piv { diff --git a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/SimpleKeyCollector.cs b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/SimpleKeyCollector.cs index 8bb8e1e1..8a20927a 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/SimpleKeyCollector.cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/SimpleKeyCollector.cs @@ -12,8 +12,6 @@ // See the License for the specific language governing permissions and // limitations under the License. -using Yubico.YubiKey.Cryptography; - namespace Yubico.YubiKey.Piv { // This KeyCollector class can be used to provide the KeyCollector delegate @@ -21,6 +19,19 @@ namespace Yubico.YubiKey.Piv // It is called Simple because it returns fixed, default values. public class SimpleKeyCollector { + private static readonly byte[] _pin = + { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36 }; + + private static readonly byte[] _puk = + { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38 }; + + private static readonly byte[] _mgmtKey = + { + 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, + 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, + 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08 + }; + private readonly bool _allowRetry; public SimpleKeyCollector(bool allowRetry) @@ -35,7 +46,7 @@ public bool SimpleKeyCollectorDelegate(KeyEntryData keyEntryData) return false; } - if (keyEntryData.IsRetry == true) + if (keyEntryData.IsRetry) { if (_allowRetry == false) { @@ -82,18 +93,20 @@ public bool SimpleKeyCollectorDelegate(KeyEntryData keyEntryData) break; case KeyEntryRequest.AuthenticatePivManagementKey: - if (keyEntryData.IsRetry == true) + if (keyEntryData.IsRetry) { return false; } + currentValue = CollectMgmtKey(); break; case KeyEntryRequest.ChangePivManagementKey: - if (keyEntryData.IsRetry == true) + if (keyEntryData.IsRetry) { return false; } + currentValue = CollectMgmtKey(); newValue = CollectMgmtKey(); break; @@ -111,23 +124,10 @@ public bool SimpleKeyCollectorDelegate(KeyEntryData keyEntryData) return true; } - private static readonly byte[] _pin = - { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36 }; - public static byte[] CollectPin() => _pin; - private static readonly byte[] _puk = - { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38 }; - public static byte[] CollectPuk() => _puk; - private static readonly byte[] _mgmtKey = - { - 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, - 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, - 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08 - }; - public static byte[] CollectMgmtKey() => _mgmtKey; } } diff --git a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Scp03/ChannelMacTests.cs b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Scp03/ChannelMacTests.cs index 4f7aa030..ad92329f 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Scp03/ChannelMacTests.cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Scp03/ChannelMacTests.cs @@ -14,8 +14,8 @@ using System; using Xunit; -using Yubico.Core.Iso7816; using Yubico.Core.Buffers; +using Yubico.Core.Iso7816; namespace Yubico.YubiKey.Scp03 { diff --git a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Scp03/DerivationTests.cs b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Scp03/DerivationTests.cs index 12190a73..ed571e51 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Scp03/DerivationTests.cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Scp03/DerivationTests.cs @@ -43,7 +43,7 @@ public void Derive_GivenBadOutputLen_ThrowsSecureChannelException() [Fact] public void Derive_GivenBadKey_ThrowsArgumentException() { - _ = Assert.Throws(() => Derivation.Derive(Derivation.DDC_HOST_CRYPTOGRAM,0x40, GetBadKey(), GetHostChallenge(), GetCardChallenge())); + _ = Assert.Throws(() => Derivation.Derive(Derivation.DDC_HOST_CRYPTOGRAM, 0x40, GetBadKey(), GetHostChallenge(), GetCardChallenge())); } [Fact] diff --git a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Scp03/SessionTests.cs b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Scp03/SessionTests.cs index 82bd6ff6..2f131cf4 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Scp03/SessionTests.cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Scp03/SessionTests.cs @@ -14,9 +14,9 @@ using System; using Xunit; -using Yubico.YubiKey.Scp03.Commands; -using Yubico.Core.Iso7816; using Yubico.Core.Buffers; +using Yubico.Core.Iso7816; +using Yubico.YubiKey.Scp03.Commands; namespace Yubico.YubiKey.Scp03 { diff --git a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/U2f/Commands/EchoCommandTests.cs b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/U2f/Commands/EchoCommandTests.cs index 9f0ca930..96691009 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/U2f/Commands/EchoCommandTests.cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/U2f/Commands/EchoCommandTests.cs @@ -40,9 +40,10 @@ public void Data_PropertySetGetNonEmptyArray_ReturnsCorrectArray() { ReadOnlyMemory expectedData = new byte[] { 0x01, 0x02, 0x03 }; - var command = new EchoCommand(); - - command.Data = expectedData; + var command = new EchoCommand + { + Data = expectedData + }; Assert.True(command.Data.Span.SequenceEqual(expectedData.Span)); } diff --git a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/U2f/Commands/GetDeviceInfoCommandTests.cs b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/U2f/Commands/GetDeviceInfoCommandTests.cs index cb25ea4d..7df90045 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/U2f/Commands/GetDeviceInfoCommandTests.cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/U2f/Commands/GetDeviceInfoCommandTests.cs @@ -72,7 +72,7 @@ public void CreateResponseApdu_ReturnsCorrectType() { var responseApdu = new ResponseApdu(new byte[] { 0x90, 0x00 }); var command = new GetDeviceInfoCommand(); - var response = command.CreateResponseForApdu(responseApdu); + GetDeviceInfoResponse? response = command.CreateResponseForApdu(responseApdu); _ = Assert.IsType(response); } diff --git a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/U2f/Commands/SetPinCommandTests.cs b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/U2f/Commands/SetPinCommandTests.cs index 8e6b067e..52f88059 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/U2f/Commands/SetPinCommandTests.cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/U2f/Commands/SetPinCommandTests.cs @@ -160,7 +160,7 @@ public void CreateCommandApdu_InnerCommandGetData_ReturnsCorrectData() Assert.True(actualInnerCommandData.SequenceEqual(data)); } - [Fact] + [Fact] public void CreateResponseApdu_ReturnsCorrectType() { var responseApdu = new ResponseApdu(new byte[] { 0x90, 0x00 }); diff --git a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/U2f/Commands/VerifyFipsModeCommandTests.cs b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/U2f/Commands/VerifyFipsModeCommandTests.cs index 8ed75b10..75e639d4 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/U2f/Commands/VerifyFipsModeCommandTests.cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/U2f/Commands/VerifyFipsModeCommandTests.cs @@ -146,7 +146,7 @@ public void CreateResponseApdu_ReturnsCorrectType() { var responseApdu = new ResponseApdu(new byte[] { 0x90, 0x00 }); var command = new VerifyFipsModeCommand(); - var response = command.CreateResponseForApdu(responseApdu); + VerifyFipsModeResponse? response = command.CreateResponseForApdu(responseApdu); _ = Assert.IsType(response); } diff --git a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/U2f/RegistrationDataTests.cs b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/U2f/RegistrationDataTests.cs index 32e67f34..a5e47bcd 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/U2f/RegistrationDataTests.cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/U2f/RegistrationDataTests.cs @@ -184,8 +184,8 @@ public static byte[] GetGoodAuthDataArray() authData[0] = (byte)userPresence; authData[1] = (byte)(counter >> 24); authData[2] = (byte)(counter >> 16); - authData[3] = (byte)(counter >> 8); - authData[4] = (byte) counter; + authData[3] = (byte)(counter >> 8); + authData[4] = (byte)counter; Array.Copy(signature, 0, authData, 5, signature.Length); diff --git a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/Commands/AddCredentialCommandTests.cs b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/Commands/AddCredentialCommandTests.cs index 84b2b42d..ddd4f4b4 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/Commands/AddCredentialCommandTests.cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/Commands/AddCredentialCommandTests.cs @@ -13,10 +13,10 @@ // limitations under the License. using System; -using Yubico.Core.Iso7816; +using System.Text; using Xunit; +using Yubico.Core.Iso7816; using Yubico.Core.Tlv; -using System.Text; namespace Yubico.YubiKey.YubiHsmAuth.Commands { diff --git a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/Commands/ChangeManagementKeyCommandTests.cs b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/Commands/ChangeManagementKeyCommandTests.cs index 84455504..2ffdcdf6 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/Commands/ChangeManagementKeyCommandTests.cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/Commands/ChangeManagementKeyCommandTests.cs @@ -13,8 +13,8 @@ // limitations under the License. using System; -using Yubico.Core.Iso7816; using Xunit; +using Yubico.Core.Iso7816; using Yubico.Core.Tlv; namespace Yubico.YubiKey.YubiHsmAuth.Commands diff --git a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/Commands/GetAes128SessionKeysCommandTests.cs b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/Commands/GetAes128SessionKeysCommandTests.cs index ec532d30..88ff6bdf 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/Commands/GetAes128SessionKeysCommandTests.cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/Commands/GetAes128SessionKeysCommandTests.cs @@ -13,10 +13,10 @@ // limitations under the License. using System; -using Yubico.Core.Iso7816; +using System.Text; using Xunit; +using Yubico.Core.Iso7816; using Yubico.Core.Tlv; -using System.Text; namespace Yubico.YubiKey.YubiHsmAuth.Commands { diff --git a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/Commands/GetApplicationVersionCommandTests.cs b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/Commands/GetApplicationVersionCommandTests.cs index baafe9f6..e6be5c69 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/Commands/GetApplicationVersionCommandTests.cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/Commands/GetApplicationVersionCommandTests.cs @@ -13,8 +13,8 @@ // limitations under the License. using System; -using Yubico.Core.Iso7816; using Xunit; +using Yubico.Core.Iso7816; namespace Yubico.YubiKey.YubiHsmAuth.Commands { diff --git a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/Commands/GetManagementKeyRetriesCommandTests.cs b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/Commands/GetManagementKeyRetriesCommandTests.cs index ede3686a..378fd28e 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/Commands/GetManagementKeyRetriesCommandTests.cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/Commands/GetManagementKeyRetriesCommandTests.cs @@ -13,8 +13,8 @@ // limitations under the License. using System; -using Yubico.Core.Iso7816; using Xunit; +using Yubico.Core.Iso7816; using Yubico.Core.Tlv; namespace Yubico.YubiKey.YubiHsmAuth.Commands diff --git a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/Commands/ListCredentialsCommandTests.cs b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/Commands/ListCredentialsCommandTests.cs index c9875ec7..055ec207 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/Commands/ListCredentialsCommandTests.cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/Commands/ListCredentialsCommandTests.cs @@ -13,8 +13,8 @@ // limitations under the License. using System; -using Yubico.Core.Iso7816; using Xunit; +using Yubico.Core.Iso7816; namespace Yubico.YubiKey.YubiHsmAuth.Commands { diff --git a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/Commands/ListCredentialsResponseTests.cs b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/Commands/ListCredentialsResponseTests.cs index 6aaaba4b..bd2fc1c6 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/Commands/ListCredentialsResponseTests.cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/Commands/ListCredentialsResponseTests.cs @@ -77,7 +77,7 @@ public void GetData_DataTagAlgorithm_ThrowsMalformedException() [Fact] public void GetData_DataTagAlgorithm_ExceptionMessageInvalidDataTag() { - string expectedMessage = $"The value { DataTagConstants.CryptographicKeyType } is not " + + string expectedMessage = $"The value {DataTagConstants.CryptographicKeyType} is not " + $"a data tag supported by the YubiKey application."; byte[] dataWithoutSw = new byte[] { DataTagConstants.CryptographicKeyType, 1, 0 }; @@ -104,15 +104,19 @@ public void GetData_InvalidElementSize_ThrowsMalformedException(int labelLength) // Touch - false // Label - string of given size // Retries - 0 - List credRetryData = new List(); - credRetryData.Add((byte)CryptographicKeyType.None); - credRetryData.Add(0); + List credRetryData = new List + { + (byte)CryptographicKeyType.None, + 0 + }; credRetryData.AddRange(Encoding.UTF8.GetBytes(new char[labelLength])); credRetryData.Add(0); - List dataWithoutSw = new List(); - dataWithoutSw.Add(DataTagConstants.LabelList); - dataWithoutSw.Add((byte)credRetryData.Count); + List dataWithoutSw = new List + { + DataTagConstants.LabelList, + (byte)credRetryData.Count + }; dataWithoutSw.AddRange(credRetryData); ResponseApdu apdu = new ResponseApdu(dataWithoutSw.ToArray(), SWConstants.Success); @@ -133,15 +137,19 @@ public void GetData_ElementSize3_ExceptionMessageInvalidCredRetryDataLength() // Touch - false // Label - string of given size // Retries - 0 - List credRetryData = new List(); - credRetryData.Add((byte)CryptographicKeyType.None); - credRetryData.Add(0); + List credRetryData = new List + { + (byte)CryptographicKeyType.None, + 0 + }; credRetryData.AddRange(Encoding.UTF8.GetBytes(new char[0])); credRetryData.Add(0); - List dataWithoutSw = new List(); - dataWithoutSw.Add(DataTagConstants.LabelList); - dataWithoutSw.Add((byte)credRetryData.Count); + List dataWithoutSw = new List + { + DataTagConstants.LabelList, + (byte)credRetryData.Count + }; dataWithoutSw.AddRange(credRetryData); ResponseApdu apdu = new ResponseApdu(dataWithoutSw.ToArray(), SWConstants.Success); @@ -155,7 +163,7 @@ public void GetData_ElementSize3_ExceptionMessageInvalidCredRetryDataLength() } catch (MalformedYubiKeyResponseException ex) { - actualMessage = ex.Message; + actualMessage = ex.Message; } Assert.Equal(expectedMessage, actualMessage); @@ -187,15 +195,19 @@ public void GetData_OneElement_MatchesExpectedCredRetryObject(int labelSize) // Touch - false // Label - string of given size // Retries - 0 - List credRetryData = new List(); - credRetryData.Add((byte)expectedKeyType); - credRetryData.Add(expectedTouch ? (byte)1 : (byte)0); + List credRetryData = new List + { + (byte)expectedKeyType, + expectedTouch ? (byte)1 : (byte)0 + }; credRetryData.AddRange(Encoding.UTF8.GetBytes(expectedLabel)); credRetryData.Add(expectedRetryCount); - List dataWithoutSw = new List(); - dataWithoutSw.Add(DataTagConstants.LabelList); - dataWithoutSw.Add((byte)credRetryData.Count); + List dataWithoutSw = new List + { + DataTagConstants.LabelList, + (byte)credRetryData.Count + }; dataWithoutSw.AddRange(credRetryData); ResponseApdu apdu = new ResponseApdu(dataWithoutSw.ToArray(), SWConstants.Success); @@ -228,17 +240,20 @@ public void GetData_TwoElements_MatchesExpectedCredRetryObjects() // Touch - false // Label - string of given size // Retries - 0 - List credRetryData = new List(); - credRetryData.Add((byte)expectedKeyType); - credRetryData.Add(expectedTouch ? (byte)1 : (byte)0); + List credRetryData = new List + { + (byte)expectedKeyType, + expectedTouch ? (byte)1 : (byte)0 + }; credRetryData.AddRange(Encoding.UTF8.GetBytes(expectedLabel)); credRetryData.Add(expectedRetryCount); - List dataWithoutSw = new List(); - - // First element - dataWithoutSw.Add(DataTagConstants.LabelList); - dataWithoutSw.Add((byte)credRetryData.Count); + List dataWithoutSw = new List + { + // First element + DataTagConstants.LabelList, + (byte)credRetryData.Count + }; dataWithoutSw.AddRange(credRetryData); // Second element diff --git a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/Commands/ResetApplicationCommandTests.cs b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/Commands/ResetApplicationCommandTests.cs index 1a74bb9e..254857f2 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/Commands/ResetApplicationCommandTests.cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/Commands/ResetApplicationCommandTests.cs @@ -13,8 +13,8 @@ // limitations under the License. using System; -using Yubico.Core.Iso7816; using Xunit; +using Yubico.Core.Iso7816; namespace Yubico.YubiKey.YubiHsmAuth.Commands { diff --git a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/CredentialRetryPairTests.cs b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/CredentialRetryPairTests.cs index 5cdcf80a..05b2a02b 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/CredentialRetryPairTests.cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/CredentialRetryPairTests.cs @@ -19,7 +19,7 @@ namespace Yubico.YubiKey.YubiHsmAuth { public class CredentialRetryPairTests { - Credential cred = new Credential() + readonly Credential cred = new Credential() { KeyType = CryptographicKeyType.Aes128, TouchRequired = false, diff --git a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/CredentialTests.cs b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/CredentialTests.cs index 4f873ca0..03a6db2b 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/CredentialTests.cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/CredentialTests.cs @@ -24,7 +24,7 @@ public class CredentialTests public void Constructor_KeyTypeAes128_ObjectKeyTypeAes128() { CryptographicKeyType expectedKeyType = CryptographicKeyType.Aes128; - + Credential cred = new Credential( expectedKeyType, "test key", @@ -57,7 +57,7 @@ public void Constructor_KeyTypeNegative1_ThrowsArgOutOfRangeException() public void Constructor_LabelTestKey_ObjectLabelTestKey() { string expectedLabel = "test key"; - + Credential cred = new Credential( CryptographicKeyType.Aes128, expectedLabel, @@ -102,9 +102,10 @@ public void KeyType_GetSetAes128_KeyTypeIsAes128() Credential cred = new Credential( CryptographicKeyType.Aes128, "test key", - false); - - cred.KeyType = expectedKeyType; + false) + { + KeyType = expectedKeyType + }; Assert.Equal(expectedKeyType, cred.KeyType); } @@ -161,9 +162,10 @@ public void Label_SetGetLabel_ReturnsMatchingString(int labelLength) Credential cred = new Credential( CryptographicKeyType.Aes128, "old label", - false); - - cred.Label = expectedLabel; + false) + { + Label = expectedLabel + }; Assert.Equal(expectedLabel, cred.Label); } @@ -208,9 +210,10 @@ public void TouchRequired_SetGetTrue_ReturnsTrue() Credential cred = new Credential( CryptographicKeyType.Aes128, "test key", - false); - - cred.TouchRequired = expectedTouch; + false) + { + TouchRequired = expectedTouch + }; Assert.Equal(expectedTouch, cred.TouchRequired); } diff --git a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiKeyFeaturesTests.cs b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiKeyFeaturesTests.cs index be2a0729..5b9ab868 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiKeyFeaturesTests.cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiKeyFeaturesTests.cs @@ -13,8 +13,8 @@ // limitations under the License. using System; -using Yubico.YubiKey.TestUtilities; using Xunit; +using Yubico.YubiKey.TestUtilities; namespace Yubico.YubiKey { @@ -306,5 +306,5 @@ public void HasFeature_YubiHsmAuthApplication( Assert.Equal(expectedResult, actualResult); } -} + } } diff --git a/Yubico.YubiKey/tests/utilities/Yubico.YubiKey.TestUtilities.csproj b/Yubico.YubiKey/tests/utilities/Yubico.YubiKey.TestUtilities.csproj index 1979b34c..48a1f777 100644 --- a/Yubico.YubiKey/tests/utilities/Yubico.YubiKey.TestUtilities.csproj +++ b/Yubico.YubiKey/tests/utilities/Yubico.YubiKey.TestUtilities.csproj @@ -32,6 +32,7 @@ limitations under the License. --> + diff --git a/Yubico.YubiKey/tests/utilities/Yubico/YubiKey/TestUtilities/BioFido2Fixture.cs b/Yubico.YubiKey/tests/utilities/Yubico/YubiKey/TestUtilities/BioFido2Fixture.cs index e20cdf29..9129d4c9 100644 --- a/Yubico.YubiKey/tests/utilities/Yubico/YubiKey/TestUtilities/BioFido2Fixture.cs +++ b/Yubico.YubiKey/tests/utilities/Yubico/YubiKey/TestUtilities/BioFido2Fixture.cs @@ -13,14 +13,14 @@ // limitations under the License. using System; -using System.Linq; -using System.Text; -using System.Globalization; using System.Collections.Generic; +using System.Globalization; +using System.Linq; using System.Security.Cryptography; +using System.Text; +using Yubico.YubiKey.Cryptography; using Yubico.YubiKey.Fido2; using Yubico.YubiKey.Fido2.Commands; -using Yubico.YubiKey.Cryptography; namespace Yubico.YubiKey.TestUtilities { @@ -42,10 +42,9 @@ public class BioFido2Fixture : SimpleIntegrationTestConnection // Find the YubikKey Bio, reset it, then set the PIN to "123456" public BioFido2Fixture() - : base(YubiKeyApplication.Fido2, StandardTestDevice.Bio) + : base(YubiKeyApplication.Fido2, StandardTestDevice.Fw5Bio) { - var newPin = new ReadOnlyMemory(new byte[] { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36 }); - _resetObj = new Fido2ResetForTest(SerialNumber, newPin); + _resetObj = new Fido2ResetForTest(SerialNumber); if (_resetObj.RunFido2Reset() != ResponseStatus.Success) { throw new InvalidOperationException("Could not Reset the YubiKey"); @@ -105,7 +104,7 @@ public RpInfo MatchRelyingParty(RelyingParty relyingParty) // Get the UserEntity/MakeCredentialData pair out of the RpInfoList that // matches the given RP and User. - public Tuple MatchUser(RelyingParty relyingParty, UserEntity user) + public Tuple MatchUser(RelyingParty relyingParty, UserEntity user) { RpInfo rpInfo = MatchRelyingParty(relyingParty); UserEntity[] userArray = rpInfo.Users.Keys.ToArray(); diff --git a/Yubico.YubiKey/tests/utilities/Yubico/YubiKey/TestUtilities/CertConverter.cs b/Yubico.YubiKey/tests/utilities/Yubico/YubiKey/TestUtilities/CertConverter.cs index e833f7e4..f7251af3 100644 --- a/Yubico.YubiKey/tests/utilities/Yubico/YubiKey/TestUtilities/CertConverter.cs +++ b/Yubico.YubiKey/tests/utilities/Yubico/YubiKey/TestUtilities/CertConverter.cs @@ -150,7 +150,7 @@ public PivPublicKey GetPivPublicKey() case PivAlgorithm.Rsa1024: case PivAlgorithm.Rsa2048: - var rsaObject = _certificateObject.PublicKey.GetRSAPublicKey()!; + RSA? rsaObject = _certificateObject.PublicKey.GetRSAPublicKey()!; RSAParameters rsaParams = rsaObject.ExportParameters(false); return new PivRsaPublicKey(rsaParams.Modulus, rsaParams.Exponent); @@ -169,9 +169,9 @@ public PivPublicKey GetPivPublicKey() // throw an exception. public RSA GetRsaObject() { - if ((Algorithm == PivAlgorithm.Rsa1024) || (Algorithm == PivAlgorithm.Rsa2048)) + if (Algorithm == PivAlgorithm.Rsa1024 || Algorithm == PivAlgorithm.Rsa2048) { - var rsaObject = _certificateObject.PublicKey.GetRSAPublicKey()!; + RSA? rsaObject = _certificateObject.PublicKey.GetRSAPublicKey()!; RSAParameters rsaParams = rsaObject.ExportParameters(false); return RSA.Create(rsaParams); diff --git a/Yubico.YubiKey/tests/utilities/Yubico/YubiKey/TestUtilities/DeviceReset.cs b/Yubico.YubiKey/tests/utilities/Yubico/YubiKey/TestUtilities/DeviceReset.cs index 7fe689ec..b32a4ea9 100644 --- a/Yubico.YubiKey/tests/utilities/Yubico/YubiKey/TestUtilities/DeviceReset.cs +++ b/Yubico.YubiKey/tests/utilities/Yubico/YubiKey/TestUtilities/DeviceReset.cs @@ -13,10 +13,10 @@ // limitations under the License. using System; -using Yubico.YubiKey.Piv; +using System.Linq; using Yubico.YubiKey.Oath; +using Yubico.YubiKey.Piv; using Yubico.YubiKey.YubiHsmAuth; -using System.Linq; namespace Yubico.YubiKey.TestUtilities { @@ -132,7 +132,7 @@ private static IYubiKeyDevice SetEnabledUsbCapabilities( ResetAfterConfig = true, }; - IYubiKeyResponse setDeviceInfoResponse = SetDeviceInfo(key,setCommand); + IYubiKeyResponse setDeviceInfoResponse = SetDeviceInfo(key, setCommand); if (setDeviceInfoResponse.Status != ResponseStatus.Success) { diff --git a/Yubico.YubiKey/tests/utilities/Yubico/YubiKey/TestUtilities/Fido2ResetForTest.cs b/Yubico.YubiKey/tests/utilities/Yubico/YubiKey/TestUtilities/Fido2ResetForTest.cs index 463ca488..369d25d4 100644 --- a/Yubico.YubiKey/tests/utilities/Yubico/YubiKey/TestUtilities/Fido2ResetForTest.cs +++ b/Yubico.YubiKey/tests/utilities/Yubico/YubiKey/TestUtilities/Fido2ResetForTest.cs @@ -14,10 +14,11 @@ using System; using System.Globalization; +using System.Text; using System.Threading; using System.Threading.Tasks; -using Yubico.YubiKey.Fido2.Commands; using Yubico.YubiKey.Fido2; +using Yubico.YubiKey.Fido2.Commands; namespace Yubico.YubiKey.TestUtilities { @@ -28,19 +29,12 @@ namespace Yubico.YubiKey.TestUtilities public class Fido2ResetForTest { private const int ReinsertTimeoutSeconds = 10; + private readonly KeyEntryData _keyEntryData = new KeyEntryData(); + private readonly ReadOnlyMemory _pin; + private readonly bool _setPin; private readonly string ReinsertTimeoutString = ReinsertTimeoutSeconds.ToString(NumberFormatInfo.InvariantInfo); private IYubiKeyDevice? _yubiKeyDevice; - private readonly bool _setPin; - private readonly ReadOnlyMemory _pin; - private readonly KeyEntryData _keyEntryData = new KeyEntryData(); - - - // Set the serial number using this property. If there is no serial - // number (the actual YubiKey's serial number is null), this will be 0. - public int SerialNumber { get; private set; } - - public Func KeyCollector { get; private set; } private Fido2ResetForTest() { @@ -69,12 +63,14 @@ private Fido2ResetForTest() // object will use the default key collector. Otherwise, pass in the // alternate key collector you want this object to use. public Fido2ResetForTest( - int? serialNumber, ReadOnlyMemory? newPin = null, Func? keyCollector = null) + int? serialNumber, + ReadOnlyMemory? newPin = null, + Func? keyCollector = null) { SerialNumber = serialNumber ?? 0; if (newPin is null) { - _pin = new ReadOnlyMemory(new byte[] { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36 }); + _pin = Encoding.UTF8.GetBytes("123456"); _setPin = false; } else @@ -83,12 +79,21 @@ public Fido2ResetForTest( { throw new ArgumentException("PIN is too short"); } + _pin = new ReadOnlyMemory(newPin.Value.ToArray()); _setPin = true; } + KeyCollector = keyCollector ?? ResetForTestKeyCollector; } + + // Set the serial number using this property. If there is no serial + // number (the actual YubiKey's serial number is null), this will be 0. + private int SerialNumber { get; } + + public Func KeyCollector { get; } + public ResponseStatus RunFido2Reset() { _yubiKeyDevice = null; @@ -185,7 +190,7 @@ 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) { if (!fido2Session.TrySetPin(_pin)) { @@ -260,11 +265,13 @@ private void YubiKeyRemoved(object? sender, YubiKeyDeviceEventArgs eventArgs) { WriteMessageBox("The YubiKey removed is not the expected YubiKey." + "\nexpected serial number = " + SerialNumber.ToString(NumberFormatInfo.InvariantInfo) + - "\n removed serial number = " + serialNumberRemoved.ToString(NumberFormatInfo.InvariantInfo)); + "\n removed serial number = " + + serialNumberRemoved.ToString(NumberFormatInfo.InvariantInfo)); } else { - WriteMessageBox(" removed serial number = " + serialNumberRemoved.ToString(NumberFormatInfo.InvariantInfo)); + WriteMessageBox(" removed serial number = " + + serialNumberRemoved.ToString(NumberFormatInfo.InvariantInfo)); } } @@ -276,11 +283,13 @@ private void YubiKeyInserted(object? sender, YubiKeyDeviceEventArgs eventArgs) { WriteMessageBox("The YubiKey inserted is not the expected YubiKey." + "\nexpected serial number = " + SerialNumber.ToString(NumberFormatInfo.InvariantInfo) + - "\ninserted serial number = " + serialNumberInserted.ToString(NumberFormatInfo.InvariantInfo)); + "\ninserted serial number = " + + serialNumberInserted.ToString(NumberFormatInfo.InvariantInfo)); } else { - WriteMessageBox("inserted serial number = " + serialNumberInserted.ToString(NumberFormatInfo.InvariantInfo)); + WriteMessageBox("inserted serial number = " + + serialNumberInserted.ToString(NumberFormatInfo.InvariantInfo)); _yubiKeyDevice = eventArgs.Device; } } @@ -302,21 +311,19 @@ public static bool ResetKeyCollector(KeyEntryData keyEntryData, ReadOnlyMemory toSubmit = pin ?? new ReadOnlyMemory(new byte[] { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36 }); + ReadOnlyMemory toSubmit = + pin ?? new ReadOnlyMemory(new byte[] { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36 }); keyEntryData.SubmitValue(toSubmit.Span); return true; @@ -328,6 +335,14 @@ public static bool ResetKeyCollector(KeyEntryData keyEntryData, ReadOnlyMemory Status.ShortPressConfigured; diff --git a/Yubico.YubiKey/tests/utilities/Yubico/YubiKey/TestUtilities/IntegrationTestDeviceEnumeration.cs b/Yubico.YubiKey/tests/utilities/Yubico/YubiKey/TestUtilities/IntegrationTestDeviceEnumeration.cs index 7307ad57..e6281d23 100644 --- a/Yubico.YubiKey/tests/utilities/Yubico/YubiKey/TestUtilities/IntegrationTestDeviceEnumeration.cs +++ b/Yubico.YubiKey/tests/utilities/Yubico/YubiKey/TestUtilities/IntegrationTestDeviceEnumeration.cs @@ -66,10 +66,9 @@ private static string GetPath(string appDataSubDirectory, string filename) => public static IList GetTestDevices(Transport transport = Transport.All) { IEnumerable yubiKeyList = YubiKeyDevice.FindByTransport(transport); - IEnumerable testYubiKeys = yubiKeyList .Where(key => key.SerialNumber == null || - !Instance.blockedSerialNumbers.Contains(key.SerialNumber.Value.ToString())); + !Instance.blockedSerialNumbers.Contains(key.SerialNumber.Value.ToString())); return testYubiKeys.ToList(); } diff --git a/Yubico.YubiKey/tests/utilities/Yubico/YubiKey/TestUtilities/KeyConverter.cs b/Yubico.YubiKey/tests/utilities/Yubico/YubiKey/TestUtilities/KeyConverter.cs index 4701938e..76f48453 100644 --- a/Yubico.YubiKey/tests/utilities/Yubico/YubiKey/TestUtilities/KeyConverter.cs +++ b/Yubico.YubiKey/tests/utilities/Yubico/YubiKey/TestUtilities/KeyConverter.cs @@ -75,9 +75,6 @@ public class KeyConverter private const int PublicStartLength = 26; private const int PublicEndLength = 24; - private PivPrivateKey _pivPrivateKey = new PivPrivateKey(); - private PivPublicKey _pivPublicKey = new PivPublicKey(); - // Use these values in the method IsKeyAvailable to query whether a // particular key can be returned. public const int KeyTypePemPublic = 1; @@ -89,8 +86,8 @@ public class KeyConverter public const int KeyTypePivPublic = 7; public const int KeyTypePivPrivate = 8; - public bool IsPrivate { get; private set; } - public PivAlgorithm Algorithm { get; private set; } + private PivPrivateKey _pivPrivateKey = new PivPrivateKey(); + private PivPublicKey _pivPublicKey = new PivPublicKey(); // Build a local key object from the "string". If the string is for a // private key, it will build a private key, if it is for a public key, @@ -121,11 +118,11 @@ public class KeyConverter public KeyConverter(char[] pemKeyString) { // Search for the PublicKeyStart and End or PrivateKeyStart and End. - if (VerifyPemHeaderAndFooter(pemKeyString, PublicKeyStart.ToCharArray(), PublicKeyEnd.ToCharArray()) == true) + if (VerifyPemHeaderAndFooter(pemKeyString, PublicKeyStart.ToCharArray(), PublicKeyEnd.ToCharArray())) { BuildPivPublicKey(pemKeyString); } - else if (VerifyPemHeaderAndFooter(pemKeyString, PrivateKeyStart.ToCharArray(), PrivateKeyEnd.ToCharArray()) == true) + else if (VerifyPemHeaderAndFooter(pemKeyString, PrivateKeyStart.ToCharArray(), PrivateKeyEnd.ToCharArray())) { BuildPivPrivateKey(pemKeyString); } @@ -141,6 +138,7 @@ public KeyConverter(PivPublicKey pivPublicKey) { _pivPublicKey = PivPublicKey.Create(pivPublicKey.PivEncodedPublicKey); } + SetProperties(true); } @@ -158,6 +156,7 @@ public KeyConverter(PivPrivateKey pivPrivateKey) { _pivPrivateKey = PivPrivateKey.Create(pivPrivateKey.EncodedPrivateKey); } + SetProperties(true); } @@ -172,10 +171,11 @@ public KeyConverter(PivPrivateKey pivPrivateKey) // even if the RSA object contains the private key. public KeyConverter(RSA rsaObject, bool isPrivate) { - if (isPrivate == true) + if (isPrivate) { BuildPivPrivateKey(rsaObject); } + BuildPivPublicKey(rsaObject); SetProperties(true); @@ -192,15 +192,19 @@ public KeyConverter(RSA rsaObject, bool isPrivate) // even if the ECDsa object contains the private key. public KeyConverter(ECDsa eccObject, bool isPrivate) { - if (isPrivate == true) + if (isPrivate) { BuildPivPrivateKey(eccObject); } + BuildPivPublicKey(eccObject); SetProperties(true); } + public bool IsPrivate { get; private set; } + public PivAlgorithm Algorithm { get; private set; } + // This lets you know if you will be able to get a particular key out of // this object. // The keyType argument is one of the "KeyType" values defined in this @@ -236,6 +240,7 @@ public bool IsKeyAvailable(int keyType) { returnValue = true; } + break; case KeyTypePemPrivate: @@ -243,9 +248,10 @@ public bool IsKeyAvailable(int keyType) { break; } + // If the algorithm is ECC there has to be a public key as // well, or else we can't return a PEM key string. - if ((Algorithm == PivAlgorithm.EccP256) || (Algorithm == PivAlgorithm.EccP384)) + if (Algorithm == PivAlgorithm.EccP256 || Algorithm == PivAlgorithm.EccP384) { if (_pivPublicKey.Algorithm == PivAlgorithm.None) { @@ -257,34 +263,41 @@ public bool IsKeyAvailable(int keyType) break; case KeyTypeRsaPublic: - if ((Algorithm == PivAlgorithm.Rsa1024) || (Algorithm == PivAlgorithm.Rsa2048)) + if (Algorithm == PivAlgorithm.Rsa1024 || Algorithm == PivAlgorithm.Rsa2048) { returnValue = true; } + break; case KeyTypeRsaPrivate: - if ((_pivPrivateKey.Algorithm == PivAlgorithm.Rsa1024) || (_pivPrivateKey.Algorithm == PivAlgorithm.Rsa2048)) + if (_pivPrivateKey.Algorithm == PivAlgorithm.Rsa1024 || + _pivPrivateKey.Algorithm == PivAlgorithm.Rsa2048) { returnValue = true; } + break; case KeyTypeECDsaPublic: - if ((_pivPublicKey.Algorithm == PivAlgorithm.EccP256) || (_pivPublicKey.Algorithm == PivAlgorithm.EccP384)) + if (_pivPublicKey.Algorithm == PivAlgorithm.EccP256 || + _pivPublicKey.Algorithm == PivAlgorithm.EccP384) { returnValue = true; } + break; case KeyTypeECDsaPrivate: - if ((_pivPrivateKey.Algorithm == PivAlgorithm.EccP256) || (_pivPrivateKey.Algorithm == PivAlgorithm.EccP384)) + if (_pivPrivateKey.Algorithm == PivAlgorithm.EccP256 || + _pivPrivateKey.Algorithm == PivAlgorithm.EccP384) { if (_pivPublicKey.Algorithm != PivAlgorithm.None) { returnValue = true; } } + break; case KeyTypePivPublic: @@ -292,6 +305,7 @@ public bool IsKeyAvailable(int keyType) { returnValue = true; } + break; case KeyTypePivPrivate: @@ -299,6 +313,7 @@ public bool IsKeyAvailable(int keyType) { returnValue = true; } + break; } @@ -319,7 +334,7 @@ public PivPublicKey GetPivPublicKey() return PivPublicKey.Create(_pivPublicKey.PivEncodedPublicKey); } - if ((_pivPrivateKey.Algorithm == PivAlgorithm.Rsa1024) || (_pivPrivateKey.Algorithm == PivAlgorithm.Rsa2048)) + if (_pivPrivateKey.Algorithm == PivAlgorithm.Rsa1024 || _pivPrivateKey.Algorithm == PivAlgorithm.Rsa2048) { byte[] primeP = Array.Empty(); byte[] primeQ = Array.Empty(); @@ -378,7 +393,8 @@ public RSA GetRsaObject() try { - if ((_pivPrivateKey.Algorithm == PivAlgorithm.Rsa1024) || (_pivPrivateKey.Algorithm == PivAlgorithm.Rsa2048)) + if (_pivPrivateKey.Algorithm == PivAlgorithm.Rsa1024 || + _pivPrivateKey.Algorithm == PivAlgorithm.Rsa2048) { var rsaPrivate = (PivRsaPrivateKey)_pivPrivateKey; rsaParams.P = rsaPrivate.PrimeP.ToArray(); @@ -393,7 +409,7 @@ public RSA GetRsaObject() return RSA.Create(rsaParams); } - if ((_pivPublicKey.Algorithm == PivAlgorithm.Rsa1024) || (_pivPublicKey.Algorithm == PivAlgorithm.Rsa2048)) + if (_pivPublicKey.Algorithm == PivAlgorithm.Rsa1024 || _pivPublicKey.Algorithm == PivAlgorithm.Rsa2048) { var rsaPublic = (PivRsaPublicKey)_pivPublicKey; rsaParams.Modulus = rsaPublic.Modulus.ToArray(); @@ -442,8 +458,10 @@ public ECDsa GetEccObject() CultureInfo.CurrentCulture, RequestedKeyMessage)); } + eccCurve = ECCurve.CreateFromValue("1.3.132.0.34"); } + var eccParams = new ECParameters { Curve = (ECCurve)eccCurve @@ -513,7 +531,7 @@ public char[] GetPemKeyString() try { - if ((Algorithm == PivAlgorithm.Rsa1024) || (Algorithm == PivAlgorithm.Rsa2048)) + if (Algorithm == PivAlgorithm.Rsa1024 || Algorithm == PivAlgorithm.Rsa2048) { using RSA rsaObject = GetRsaObject(); if (IsPrivate) @@ -525,7 +543,7 @@ public char[] GetPemKeyString() encodedKey = rsaObject.ExportSubjectPublicKeyInfo(); } } - else if ((Algorithm == PivAlgorithm.EccP256) || (Algorithm == PivAlgorithm.EccP384)) + else if (Algorithm == PivAlgorithm.EccP256 || Algorithm == PivAlgorithm.EccP384) { using ECDsa eccObject = GetEccObject(); if (IsPrivate) @@ -610,7 +628,7 @@ private void SetProperties(bool exceptionOnNoData) Algorithm = _pivPublicKey.Algorithm; } - if ((exceptionOnNoData == true) && (Algorithm == PivAlgorithm.None)) + if (exceptionOnNoData && Algorithm == PivAlgorithm.None) { throw new InvalidOperationException( string.Format( @@ -883,7 +901,7 @@ public static BigInteger Egcd( private static int ReadTagLen(byte[] buffer, int offset, bool readValue) { // Make sure there are enough bytes to read. - if ((offset < 0) || (buffer.Length < offset + 2)) + if (offset < 0 || buffer.Length < offset + 2) { return -1; } @@ -896,10 +914,11 @@ private static int ReadTagLen(byte[] buffer, int offset, bool readValue) // beyond 83). This says the length is the next 1, 2, or 3 octets. int length = buffer[offset + 1]; int increment = 2; - if ((length == 0x80) || (length > 0x83)) + if (length == 0x80 || length > 0x83) { return -1; } + if (length > 0x80) { int count = length & 0xf; @@ -907,6 +926,7 @@ private static int ReadTagLen(byte[] buffer, int offset, bool readValue) { return -1; } + increment += count; length = 0; while (count > 0) @@ -935,9 +955,9 @@ private static int ReadTagLen(byte[] buffer, int offset, bool readValue) private static bool VerifyPemHeaderAndFooter(char[] pemKeyString, char[] targetStart, char[] targetEnd) { bool returnValue = false; - if (pemKeyString.Length > (targetStart.Length + targetEnd.Length)) + if (pemKeyString.Length > targetStart.Length + targetEnd.Length) { - if (CompareToTarget(pemKeyString, 0, targetStart) == true) + if (CompareToTarget(pemKeyString, 0, targetStart)) { returnValue = CompareToTarget(pemKeyString, pemKeyString.Length - targetEnd.Length, targetEnd); } diff --git a/Yubico.YubiKey/tests/utilities/Yubico/YubiKey/TestUtilities/RandomObjectUtility.cs b/Yubico.YubiKey/tests/utilities/Yubico/YubiKey/TestUtilities/RandomObjectUtility.cs index 6c8af240..1825f2bc 100644 --- a/Yubico.YubiKey/tests/utilities/Yubico/YubiKey/TestUtilities/RandomObjectUtility.cs +++ b/Yubico.YubiKey/tests/utilities/Yubico/YubiKey/TestUtilities/RandomObjectUtility.cs @@ -97,12 +97,12 @@ public void GetBytes(byte[] data, int offset, int count) { throw new ArgumentOutOfRangeException(nameof(count)); } - if ((offset + count) > data.Length) + if (offset + count > data.Length) { throw new ArgumentException(ExceptionMessages.IncorrectDerivationLength); } - if (count > (_theBytes.Length - _offset)) + if (count > _theBytes.Length - _offset) { throw new ArgumentException(ExceptionMessages.IncorrectDerivationLength); } diff --git a/Yubico.YubiKey/tests/utilities/Yubico/YubiKey/TestUtilities/SampleKeyPairs.cs b/Yubico.YubiKey/tests/utilities/Yubico/YubiKey/TestUtilities/SampleKeyPairs.cs index eef7cb13..d58811ef 100644 --- a/Yubico.YubiKey/tests/utilities/Yubico/YubiKey/TestUtilities/SampleKeyPairs.cs +++ b/Yubico.YubiKey/tests/utilities/Yubico/YubiKey/TestUtilities/SampleKeyPairs.cs @@ -137,7 +137,8 @@ public static void GetPemKeyPair(PivAlgorithm algorithm, out string publicKey, o // PivPrivateKey. public static PivPrivateKey GetPrivateKey(PivAlgorithm algorithm) => algorithm switch { - PivAlgorithm.Rsa1024 => PivPrivateKey.Create(new byte[] { + PivAlgorithm.Rsa1024 => PivPrivateKey.Create(new byte[] + { 0x01, 0x40, 0xdf, 0x2c, 0x15, 0xe7, 0x9f, 0xf7, 0xf0, 0xe4, 0x36, 0xfd, 0x93, 0x1f, 0xd7, 0x36, 0x20, 0x2e, 0x70, 0xd2, 0x51, 0xe4, 0x4a, 0x5d, 0xf8, 0xbb, 0xfd, 0x2d, 0x66, 0xd1, 0xe5, 0x1d, 0x5e, 0x92, @@ -165,7 +166,8 @@ public static void GetPemKeyPair(PivAlgorithm algorithm, out string publicKey, o 0xfd, 0xda, 0x5b, 0xbb, 0xc1, 0x0a, 0x77, 0x73, 0x0a, 0xaa, 0x1e, 0xc5, 0x66, 0x42, 0x96, 0xcf }), - PivAlgorithm.Rsa2048 => PivPrivateKey.Create(new byte[] { + PivAlgorithm.Rsa2048 => PivPrivateKey.Create(new byte[] + { 0x02, 0x81, 0x80, 0xcf, 0xd5, 0x17, 0xb1, 0x3c, 0x65, 0x10, 0xb9, 0x02, 0xc8, 0x0b, 0xd8, 0xfb, 0xb3, 0x2d, 0xec, 0x5c, 0x33, 0x24, 0x50, 0xd6, 0x0f, 0x13, 0xb4, 0x31, 0xcb, 0x41, 0xfc, 0x7c, 0x60, 0xbf, 0x2a, @@ -213,13 +215,15 @@ public static void GetPemKeyPair(PivAlgorithm algorithm, out string publicKey, o 0x39, 0x18, 0xc1, 0x5d, 0xd4, 0x66, 0x4b, 0x07, 0xc3, 0x79, 0x57, 0x20, 0xd6, 0x78, 0xad, 0xab, }), - PivAlgorithm.EccP256 => PivPrivateKey.Create(new byte[] { + PivAlgorithm.EccP256 => PivPrivateKey.Create(new byte[] + { 0x06, 0x20, 0xba, 0x29, 0x7a, 0xc6, 0x64, 0x62, 0xef, 0x6c, 0xd0, 0x89, 0x76, 0x5c, 0xbd, 0x46, 0x52, 0x2b, 0xb0, 0x48, 0x0e, 0x85, 0x49, 0x15, 0x85, 0xe7, 0x7a, 0x74, 0x3c, 0x8e, 0x03, 0x59, 0x8d, 0x3a }), - _ => PivPrivateKey.Create(new byte[] { + _ => PivPrivateKey.Create(new byte[] + { 0x06, 0x30, 0x47, 0x85, 0xde, 0x3a, 0xff, 0x10, 0x0d, 0x67, 0xa7, 0x26, 0x30, 0x62, 0x73, 0x45, 0xfd, 0xce, 0xeb, 0xb9, 0xbe, 0x4c, 0x93, 0x42, 0xcd, 0x6a, 0x84, 0xd6, 0x8e, 0x00, 0x70, 0x70, 0x4c, 0x66, @@ -233,7 +237,8 @@ public static void GetPemKeyPair(PivAlgorithm algorithm, out string publicKey, o public static bool GetMatchingKeyAndCert( out X509Certificate2 cert, out PivPrivateKey privateKey) { - byte[] certDer = new byte[] { + byte[] certDer = new byte[] + { 0x30, 0x82, 0x03, 0xAE, 0x30, 0x82, 0x02, 0x96, 0xA0, 0x03, 0x02, 0x01, 0x02, 0x02, 0x09, 0x00, 0xCB, 0x4C, 0xB9, 0x7C, 0x9B, 0xF1, 0x88, 0xD6, 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x0B, 0x05, 0x00, 0x30, 0x6C, 0x31, 0x0B, 0x30, 0x09, 0x06, 0x03, 0x55, @@ -295,7 +300,8 @@ public static bool GetMatchingKeyAndCert( 0xDB, 0x0B, 0x22, 0x73, 0x9C, 0x98, 0x68, 0xE1, 0xFC, 0xDA, 0x5E, 0x8B, 0xB3, 0xDB, 0x28, 0x2A, 0x69, 0x00 }; - byte[] keyData = new byte[] { + byte[] keyData = new byte[] + { 0x01, 0x81, 0x80, 0xdf, 0x4d, 0x54, 0xdb, 0x53, 0x94, 0xe6, 0x62, 0x1b, 0xfb, 0xe7, 0x92, 0xe9, 0x5c, 0x57, 0xa1, 0xfb, 0xe9, 0x52, 0xb3, 0xba, 0x7b, 0x57, 0x9c, 0x03, 0xb4, 0xa5, 0x80, 0xe6, 0xe5, 0xbb, 0x9a, @@ -363,7 +369,8 @@ public static bool GetMatchingKeyAndCert( // These keys and certs can be used for anything, they don't have to be // used in attestation. That is, if you are not dealing with attestation, // and you need a key and cert, these might work. - public static bool GetKeyAndCertPem(PivAlgorithm algorithm, bool validAttest, out string cert, out string privateKey) + public static bool GetKeyAndCertPem(PivAlgorithm algorithm, bool validAttest, out string cert, + out string privateKey) { switch (algorithm) { @@ -373,7 +380,7 @@ public static bool GetKeyAndCertPem(PivAlgorithm algorithm, bool validAttest, ou return false; case PivAlgorithm.Rsa1024: - if (validAttest == true) + if (validAttest) { cert = "-----BEGIN CERTIFICATE-----\n" + @@ -416,6 +423,7 @@ public static bool GetKeyAndCertPem(PivAlgorithm algorithm, bool validAttest, ou "BRl88HhQ1aHTDbx3b8ahshSdbhG6JLmGfZBdp18XPljnwQ==\n" + "-----END CERTIFICATE-----"; } + privateKey = "-----BEGIN PRIVATE KEY-----\n" + "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBALG/a85wy36uf4Rm\n" + @@ -437,7 +445,7 @@ public static bool GetKeyAndCertPem(PivAlgorithm algorithm, bool validAttest, ou break; case PivAlgorithm.Rsa2048: - if (validAttest == true) + if (validAttest) { cert = "-----BEGIN CERTIFICATE-----\n" + @@ -486,6 +494,7 @@ public static bool GetKeyAndCertPem(PivAlgorithm algorithm, bool validAttest, ou "WvIT54DcVb+MwcRQvCyzgcWxekMtPg==\n" + "-----END CERTIFICATE-----"; } + privateKey = "-----BEGIN PRIVATE KEY-----\n" + "MIIEwAIBADANBgkqhkiG9w0BAQEFAASCBKowggSmAgEAAoIBAQDbf2A4p7asu6sn\n" + @@ -519,7 +528,7 @@ public static bool GetKeyAndCertPem(PivAlgorithm algorithm, bool validAttest, ou break; case PivAlgorithm.EccP256: - if (validAttest == true) + if (validAttest) { cert = "-----BEGIN CERTIFICATE-----\n" + @@ -570,7 +579,7 @@ public static bool GetKeyAndCertPem(PivAlgorithm algorithm, bool validAttest, ou break; case PivAlgorithm.EccP384: - if (validAttest == true) + if (validAttest) { cert = "-----BEGIN CERTIFICATE-----\n" + @@ -611,6 +620,7 @@ public static bool GetKeyAndCertPem(PivAlgorithm algorithm, bool validAttest, ou "e510vuxfCvR7kt74bSuKi3wxsCTLtMEfIh51k3xZsa4FoLO8mm4v\n" + "-----END CERTIFICATE-----"; } + privateKey = "-----BEGIN PRIVATE KEY-----\n" + "MIG2AgEAMBAGByqGSM49AgEGBSuBBAAiBIGeMIGbAgEBBDAKroxlCShQ6sz89gMc\n" + diff --git a/Yubico.YubiKey/tests/utilities/Yubico/YubiKey/TestUtilities/SimpleIntegrationTestConnection.cs b/Yubico.YubiKey/tests/utilities/Yubico/YubiKey/TestUtilities/SimpleIntegrationTestConnection.cs index 8ddfe648..571ebb65 100644 --- a/Yubico.YubiKey/tests/utilities/Yubico/YubiKey/TestUtilities/SimpleIntegrationTestConnection.cs +++ b/Yubico.YubiKey/tests/utilities/Yubico/YubiKey/TestUtilities/SimpleIntegrationTestConnection.cs @@ -34,7 +34,8 @@ public class SimpleIntegrationTestConnection : IDisposable _serialNumber ?? throw new InvalidOperationException("No serial number."); public SimpleIntegrationTestConnection( - YubiKeyApplication application, StandardTestDevice device = StandardTestDevice.Fw5) + YubiKeyApplication application, + StandardTestDevice device = StandardTestDevice.Fw5) { _device = IntegrationTestDeviceEnumeration.GetTestDevice(device); _connection = _device.Connect(application); diff --git a/Yubico.YubiKey/tests/utilities/Yubico/YubiKey/TestUtilities/StandardTestDevice.cs b/Yubico.YubiKey/tests/utilities/Yubico/YubiKey/TestUtilities/StandardTestDevice.cs index cb67ec3b..c8fb1e93 100644 --- a/Yubico.YubiKey/tests/utilities/Yubico/YubiKey/TestUtilities/StandardTestDevice.cs +++ b/Yubico.YubiKey/tests/utilities/Yubico/YubiKey/TestUtilities/StandardTestDevice.cs @@ -39,7 +39,7 @@ public enum StandardTestDevice /// /// Major version 5, USB C Lightning, not FIPS /// - Fw5ci, + Fw5Ci, /// /// Major version 5, USB C Keychain @@ -49,6 +49,6 @@ public enum StandardTestDevice /// /// Major version 5, USB A biometric keychain, not FIPS /// - Bio + Fw5Bio } } diff --git a/Yubico.YubiKey/tests/utilities/Yubico/YubiKey/TestUtilities/StaticConverters.cs b/Yubico.YubiKey/tests/utilities/Yubico/YubiKey/TestUtilities/StaticConverters.cs index ccfbb443..f594a387 100644 --- a/Yubico.YubiKey/tests/utilities/Yubico/YubiKey/TestUtilities/StaticConverters.cs +++ b/Yubico.YubiKey/tests/utilities/Yubico/YubiKey/TestUtilities/StaticConverters.cs @@ -101,9 +101,9 @@ public static byte[] ParseByteArray(string s) { // Okay, it may be delimited. First, are there any illegal // characters? - if (!Regex.IsMatch(s, $"^[\\da-fA-FxX{ delimiters }]+$")) + if (!Regex.IsMatch(s, $"^[\\da-fA-FxX{delimiters}]+$")) { - throw new ArgumentException($"[{ s }] has invalid characters and can't be parsed as a byte array."); + throw new ArgumentException($"[{s}] has invalid characters and can't be parsed as a byte array."); } // Are they likely decimal or hex? This is kind of risky. It @@ -138,7 +138,7 @@ public static byte[] ParseByteArray(string s) // I'm just going to let it throw at the bottom. } - throw new ArgumentException($"[{ s }] cannot be converted to a byte array."); + throw new ArgumentException($"[{s}] cannot be converted to a byte array."); } /// @@ -161,11 +161,11 @@ public static byte ParseSingleByte(string s) int value = Convert.ToInt32(match.Value); if (value > 0xff) { - throw new ArgumentException($"[{ s }] cannot be converted to a byte."); + throw new ArgumentException($"[{s}] cannot be converted to a byte."); } return Convert.ToByte(value); } - throw new ArgumentException($"[{ s }] cannot be converted to a byte."); + throw new ArgumentException($"[{s}] cannot be converted to a byte."); } /// @@ -189,7 +189,7 @@ public static bool ParseBool(string s) "yes" => true, "no" => false, "" => true, // If a bool parameter didn't get a value, we assume true. - _ => throw new ArgumentException($"[{ s }] can't be parsed as a bool.") + _ => throw new ArgumentException($"[{s}] can't be parsed as a bool.") }; } @@ -211,7 +211,7 @@ public static T ParseEnum(string s) where T : struct return value; } } - throw new ArgumentException($"Value [{ s }] could not be parsed as type [{ typeof(T).Name }]."); + throw new ArgumentException($"Value [{s}] could not be parsed as type [{typeof(T).Name}]."); } } } diff --git a/Yubico.YubiKey/tests/utilities/Yubico/YubiKey/TestUtilities/TestDeviceSelection.cs b/Yubico.YubiKey/tests/utilities/Yubico/YubiKey/TestUtilities/TestDeviceSelection.cs index cb63e76c..a3a4a0ad 100644 --- a/Yubico.YubiKey/tests/utilities/Yubico/YubiKey/TestUtilities/TestDeviceSelection.cs +++ b/Yubico.YubiKey/tests/utilities/Yubico/YubiKey/TestUtilities/TestDeviceSelection.cs @@ -39,10 +39,9 @@ public static IYubiKeyDevice RenewDeviceEnumeration(int serialNumber) try { - return - TestDev.GetTestDevices() - .Where(d => d.SerialNumber == serialNumber) - .Single(); + return TestDev + .GetTestDevices() + .Single(d => d.SerialNumber == serialNumber); } catch (InvalidOperationException) { @@ -62,38 +61,51 @@ public static IYubiKeyDevice RenewDeviceEnumeration(int serialNumber) /// /// Thrown when the input sequence did not contain a valid test device. /// - /// public static IYubiKeyDevice SelectRequiredTestDevice( this IEnumerable yubiKeys, StandardTestDevice testDevice) - => testDevice switch + { + IEnumerable yubiKeyDevices = yubiKeys as IYubiKeyDevice[] ?? yubiKeys.ToArray(); + if (!yubiKeyDevices.Any()) + { + throw new InvalidOperationException("Could not find any connected Yubikeys"); + } + + return testDevice switch { - StandardTestDevice.Fw3 => yubiKeys.SelectRequiredTestDevice(3, FormFactor.Unknown, false), - StandardTestDevice.Fw4Fips => yubiKeys.SelectRequiredTestDevice(4, FormFactor.Unknown, true), - StandardTestDevice.Fw5 => yubiKeys.SelectRequiredTestDevice(5, FormFactor.UsbAKeychain, false), - StandardTestDevice.Fw5C => yubiKeys.SelectRequiredTestDevice(5, FormFactor.UsbCKeychain, false), - StandardTestDevice.Fw5ci => yubiKeys.SelectRequiredTestDevice(5, FormFactor.UsbCLightning, false), - StandardTestDevice.Fw5Fips => yubiKeys.SelectRequiredTestDevice(5, FormFactor.UsbAKeychain, true), - StandardTestDevice.Bio => yubiKeys.SelectRequiredTestDevice(5, FormFactor.UsbABiometricKeychain, false), + StandardTestDevice.Fw3 => SelectDevice(3), + StandardTestDevice.Fw4Fips => SelectDevice(4, isFipsSeries: true), + StandardTestDevice.Fw5 => SelectDevice(5, formFactor: null), + StandardTestDevice.Fw5Fips => SelectDevice(5, formFactor: FormFactor.UsbAKeychain, isFipsSeries: true), + StandardTestDevice.Fw5Bio => SelectDevice(5, formFactor: FormFactor.UsbABiometricKeychain), _ => throw new ArgumentException("Invalid test device value.", nameof(testDevice)), }; - /// - /// Retrieves a single based on test device requirements. - /// - /// - /// Thrown when the input sequence did not contain a valid test device. - /// - public static IYubiKeyDevice SelectRequiredTestDevice( - this IEnumerable yubiKeys, - int? majorVersion, - FormFactor? formFactor, - bool? fipsSeries) - => yubiKeys - .Where(d => - (majorVersion is null || d.FirmwareVersion.Major == majorVersion) - && (formFactor is null || d.FormFactor == formFactor) - && (fipsSeries is null || d.IsFipsSeries == fipsSeries)) - .First(); + IYubiKeyDevice SelectDevice(int majorVersion, FormFactor? formFactor = null, bool isFipsSeries = false) + { + try + { + return yubiKeyDevices.First(d => + d.FirmwareVersion.Major == majorVersion && + (formFactor is null || d.FormFactor == formFactor) && + d.IsFipsSeries == isFipsSeries); + } + catch (InvalidOperationException) + { + string connectedDevices = yubiKeyDevices.Any() + ? "Connected devices: " + string.Join(", ", + yubiKeyDevices.Select(y => $"{{{y.FirmwareVersion}, {y.FormFactor}}}")) + : string.Empty; + throw new DeviceNotFoundException( + $"Target test device not found ({testDevice}). ({connectedDevices})"); + } + } + } + } + + // Custom test exception inheriting from InvalidOperationException as some test code depends on InvalidOperationExceptions + public class DeviceNotFoundException : InvalidOperationException + { + public DeviceNotFoundException(string message) : base(message) { } } } diff --git a/build/Versions.props b/build/Versions.props index b8d7b453..e5927050 100644 --- a/build/Versions.props +++ b/build/Versions.props @@ -40,7 +40,7 @@ for external milestones. Increment the minor version whenever we add support for a new class or type. Increment the patch version for bug fixes. --> - 1.9.1 + 1.10.0 - 1.9.1 + 1.10.0 - 1.9.1 + 1.10.0 diff --git a/coverlet.runsettings.xml b/coverlet.runsettings.xml new file mode 100644 index 00000000..114bfaf8 --- /dev/null +++ b/coverlet.runsettings.xml @@ -0,0 +1,18 @@ + + + + + + + cobertura + **/tests/**/*.cs + Obsolete,GeneratedCodeAttribute,CompilerGeneratedAttribute + + false + true + false + + + + + \ No newline at end of file diff --git a/global.json b/global.json new file mode 100644 index 00000000..2cdb7ebc --- /dev/null +++ b/global.json @@ -0,0 +1,6 @@ +{ + "sdk": { + "version": "6.0.300", + "rollForward": "latestFeature" + } +} \ No newline at end of file