Bootstrapping the blue Windows when you have random AArch64 devices in the backyard

A Nintendo Switch showing the "Windows Blue Logo"

Last year I mentioned my attempt to bootstrap Windows 10 on Dragonboard 410c. This year I ported EDK2 to Nintendo Switch and successfully booted Windows 10 arm64 installation ramdisk (rs4, rs5, and 19H1 tested as of writing time). I will briefly introduce a common way to port EDK2 with existing codebase (e.g. U-Boot), as well as cases of booting in EL2 (hypervisor).

Background

While this article applies to most ARM SoCs, the following content will use Tegra as the example. NVIDIA developed a few solutions for Windows on ARM in Windows 8 era: Tegra 3 (Tegra30) and 4 (Tegra114). No further model have official Windows BSP (Board Support Package) released publicly due to low market acceptance of those Windows RT products.

Despite of that, general AArch64 processors are capable to run Windows 10 without additional HAL extension library if the following conditions are satisfied:

  • Architecture Timer with ACPI GTDT table description. Either CP15 or MMIO clock is okay.
  • Generic Interrupt Controller v2/v3 (we are not yet aware of v4 support) with ACPI MADT (APIC) table description, or Broadcom Interrupt Controller
  • AArch64 instruction set (crypto extension is not required)
  • ARM Performance Monitor Unit with ACPI MADT (APIC) table description

One noticeable exception the initial generation of Qualcomm Kryo (Snapdragon 820, 821) due to the faulty cache design in large core cluster. Windows removed the required erratum for it due to the complication of patch maintenance.

In the case of Tegra X1, it satisfied all conditions outlined above. I used an old-bootrom Nintendo Switch as my experiment platform since it is much cheaper than Jetson TX1. Additionally, there is verified CoreBoot and U-Boot source code for these Tegra X1 devices including Nintendo Switch.

I assume you are familiar with the NVIDIA RCM Exploit (Fusee-Gelee) as well as Tegra Boot flow. If you are not familiar with Tegra Boot flow, please refer to Tegra Technical Reference Manual available on NVIDIA developer site.

Port U-Boot Code to EDK2

There are a few environment assumptions that need to be addressed while porting U-Boot device/driver code to EDK2:

  • While U-Boot runs in AArch64 context, it only utilizes little amount of memory at the memory bottom in most circumstances. EDK2/TianoCore loads everything as high as possible per UEFI specification. Certain peripheral operations are not 64-bit addressing aware. It’s okay to force converting 64-Bit pointers to 32-Bit without data loss in the U-Boot assumption, but in EDK2 this might lead to issues. One case is SDMA (single operation DMA). Tegra SDHCI controller SDMA operations are not 64-bit addressing aware. To address the issue, I slightly modified the DMA bounce buffer allocation library (also ported from U-Boot) to allocate bottom memory instead.
  • Syntax styles. U-Boot observes the Linux naming convention for functions and types; EDK2 observes the Windows style. It might be a good idea to write a shim to provide functions like readl/writel as well as udelay/mdelay.
  • There is probably no need for porting generic classes (e.g. udevice). You might not need them in EDK2 context.

To save myself some time bootstrapping the microSD slot, I ported the clock and device framework from U-Boot to EDK2. Here are a few suggestions while porting U-Boot code to EDK2:

  • Address issues mentioned above.
  • Put device specific definitions into “Include” directory, use PCD database when necessary.
  • Install these code services as DXE driver whenever possible. Invoke them using protocols.
  • For board/machine-dependent code library (e.g. mach-tegra), depends on the usage to integrate them with driver or use additional library instead.

From Device Tree to ACPI

Device Tree is the de-facto standard in ARM to describe the system and peripheral hierarchy. Windows RT introduces the intensive use of ACPI on ARM platforms. I will cover some required tables for a success Windows startup on ARM platforms. For tables such as CSRT and DSDT, check out the Microsoft documentation.

GTDT (Generic Timer Description Table)

For SoC with architecture timer, ARM defines GTDT table to describe platform timer information. In the device tree, an architectural timer may looks like this:

timer {
	compatible = "arm,armv8-timer";
	interrupts = <GIC_PPI 13 (GIC_CPU_MASK_SIMPLE(4) | IRQ_TYPE_LEVEL_LOW)>,
	             <GIC_PPI 14 (GIC_CPU_MASK_SIMPLE(4) | IRQ_TYPE_LEVEL_LOW)>,
	             <GIC_PPI 11 (GIC_CPU_MASK_SIMPLE(4) | IRQ_TYPE_LEVEL_LOW)>,
		     <GIC_PPI 10 (GIC_CPU_MASK_SIMPLE(4) | IRQ_TYPE_LEVEL_LOW)>;
	interrupt-parent = <&gic>;
};

And it looks like this in ACPI GTDT table:

....

[024h 0036   8]        Counter Block Address : FFFFFFFFFFFFFFFF
[02Ch 0044   4]                     Reserved : 00000000

[030h 0048   4]         Secure EL1 Interrupt : 0000001D
[034h 0052   4]    EL1 Flags (decoded below) : 00000002
                                Trigger Mode : 0
                                    Polarity : 1
                                   Always On : 0

[038h 0056   4]     Non-Secure EL1 Interrupt : 0000001E
[03Ch 0060   4]   NEL1 Flags (decoded below) : 00000002
                                Trigger Mode : 0
                                    Polarity : 1
                                   Always On : 0

[040h 0064   4]      Virtual Timer Interrupt : 0000001B
[044h 0068   4]     VT Flags (decoded below) : 00000002
                                Trigger Mode : 0
                                    Polarity : 1
                                   Always On : 0

[048h 0072   4]     Non-Secure EL2 Interrupt : 0000001A
[04Ch 0076   4]   NEL2 Flags (decoded below) : 00000002
                                Trigger Mode : 0
                                    Polarity : 1
                                   Always On : 0
[050h 0080   8]   Counter Read Block Address : FFFFFFFFFFFFFFFF

...
  • If your platform does not have MMIO architectural timer, write the address as 0xFFFFFFFFFFFFFFFF.
  • If you boot from EL2, you are required to supply all timer values. Otherwise only EL1 timers are needed.
  • PPI starts at 16. Plus 16 for all interrupt numbers you have in the device tree. The four interrupts are Secure EL1, Non-secure EL1, virtual timer and hypervisor in sequence.
  • You may have platform watchdog, supply it in the GTDT table too (see Qualcomm example). It is not mandatory for booting Windows though.

MADT (Multiple APIC Description Table)

Most AArch64 SoC systems have one or more GIC-compatible interrupt controllers. Windows has inbox GIC support, all needed is supplying proper information in the MADT table. The table also describes ARM Performance Monitor Unit information for system’s reference. In device tree, GIC and PMU look like this:

gic: interrupt-controller@50041000 {
	compatible = "arm,gic-400";
	#interrupt-cells = <3>;
	interrupt-controller;
	reg = <0x0 0x50041000 0x0 0x1000>,
	    <0x0 0x50042000 0x0 0x2000>,
            <0x0 0x50044000 0x0 0x2000>,
	    <0x0 0x50046000 0x0 0x2000>;
	interrupts = <GIC_PPI 9 (GIC_CPU_MASK_SIMPLE(4) | IRQ_TYPE_LEVEL_HIGH)>;
	interrupt-parent = <&gic>;
};
arm_pmu: arm-pmu {
	compatible = "arm,armv8-pmuv3";
	interrupts = <GIC_SPI 144 IRQ_TYPE_LEVEL_HIGH>,
	    <GIC_SPI 145 IRQ_TYPE_LEVEL_HIGH>,
            <GIC_SPI 146 IRQ_TYPE_LEVEL_HIGH>,
	    <GIC_SPI 147 IRQ_TYPE_LEVEL_HIGH>;
};

An example of the MADT table can be found here.

  • In MADT table, each processor core have an table entry. Make sure you have the same CPU object in DSDT table, with identical and unique UID and CPU interface ID.
  • If your platform supports ARM PSCI, parking address field can be ignored.
  • The four registers in GIC device tree are GIC distributor, GIC base address, hypervisor GIC base address and virtual GIC base address.
  • You might need to supply GIC redistributor address on GICv3 architecture.
  • SPI interrupt number starts at 32. Plus 32 for all performance interrupt number in MADT table.
  • MPIDR value needs to be referred from platform resources.

DBG2 (Microsoft Debug Table 2)

Microsoft defines DBG2 table for ARM platforms. Although Microsoft docs mark DBG2 table info as mandatory, you do not need to supply debug device information if you just want to boot Windows as a proof-of-concept :P. An empty DBG2 table is enough for booting.

For debug purposes, it is necessary to define at least one debug device (8250/16550 serial or USB) in DSDT and DBG2 table. More information can be found at here.

FADT (Fixed ACPI Description Table)

Indicates PSCI support and Hardware-reduced ACPI mode, then you are good to go.

Debugging ACPI

It’s incredibly difficult to debug early ACPI startup if you don’t have serial or debug access on the platform. Fortunately, Linux provides some utility for it. It is feasible to enable the UEFI FrameBuffer early printk support on 5.0+ kernels to simplify the debug process.

Conclusion

With much effort, Windows on ARM can run on a variety of AArch64 devices. There’s still much work between “just-booted” and “usable”, and it may cost you countless nights to achieve your marvel, even if there are always guys ask you “why”:

https://www.reddit.com/r/SwitchHacks/comments/awukbx/windows_on_switch_being_worked_on/

Fix broken Windows Management Instrumentation

A colleague told me a Windows Server 2016 node entered an inconsistent state after an abnormal shutdown. The following symptoms were observed:

  • Explorer hangs with “loading…” text
  • Hyper-V Management couldn’t connect to the local server
  • Group Policy Update consequently failed
  • Telemetry metrics disappeared
  • WMI Management reported “RPC: the requested object does not exist” for object Root

A quick diagnostics indicated a component failure with Windows Management Instrumentation. To determine the failure source, I ran WMIDiag from Microsoft. The log showed a metadata failure:

.1526 21:47:43 (1) !! ERROR: WMI CONNECTION errors occured for the following namespaces: ………………………………………….. 20 ERROR(S)!
 .1527 21:47:43 (0) ** - Root, 0x80010114 - The requested object does not exist..
 .1528 21:47:43 (0) ** - Root, 0x80010114 - The requested object does not exist..
 .1529 21:47:43 (0) ** - Root/subscription, 0x80010114 - The requested object does not exist..
 .1530 21:47:43 (0) ** - Root/DEFAULT, 0x80010114 - The requested object does not exist..
 .1531 21:47:43 (0) ** - Root/CIMV2, 0x80010114 - The requested object does not exist..
 .1532 21:47:43 (0) ** - Root/CIMV2/Security, 0x80010114 - The requested object does not exist..
 .1533 21:47:43 (0) ** - Root/CIMV2/TerminalServices, 0x80010114 - The requested object does not exist..
 .1534 21:47:43 (0) ** - Root/nap, 0x80010114 - The requested object does not exist..
 .1535 21:47:43 (0) ** - Root/SECURITY, 0x80010114 - The requested object does not exist..
 .1536 21:47:43 (0) ** - Root/STANDARDCIMV2, 0x80010114 - The requested object does not exist..
 .1537 21:47:43 (0) ** - Root/RSOP, 0x80010114 - The requested object does not exist..
 .1538 21:47:43 (0) ** - Root/RSOP/User, 0x80010114 - The requested object does not exist..
 .1539 21:47:43 (0) ** - Root/RSOP/Computer, 0x80010114 - The requested object does not exist..
 .1540 21:47:43 (0) ** - Root/WMI, 0x80010114 - The requested object does not exist..
 .1541 21:47:43 (0) ** - Root/directory, 0x80010114 - The requested object does not exist..
 .1542 21:47:43 (0) ** - Root/directory/LDAP, 0x80010114 - The requested object does not exist..
 .1543 21:47:43 (0) ** - Root/Policy, 0x80010114 - The requested object does not exist..
 .1544 21:47:43 (0) ** - Root/Microsoft, 0x80010114 - The requested object does not exist..
 .1545 21:47:43 (0) ** - Root/Microsoft/HomeNet, 0x80010114 - The requested object does not exist..
 .1546 21:47:43 (0) ** - Root/aspnet, 0x80010114 - The requested object does not exist..

The documentation suggested performing a metadata registration. The following script is utilized for the metadata repair:

@echo on
cd /d c:\temp
if not exist %windir%\system32\wbem goto TryInstall
cd /d %windir%\system32\wbem
net stop winmgmt
winmgmt /kill
if exist Rep_bak rd Rep_bak /s /q
rename Repository Rep_bak
for %%i in (*.dll) do RegSvr32 -s %%i
for %%i in (*.exe) do call :FixSrv %%i
for %%i in (*.mof,*.mfl) do Mofcomp %%i
net start winmgmt
goto End

:FixSrv
if /I (%1) == (wbemcntl.exe) goto SkipSrv
if /I (%1) == (wbemtest.exe) goto SkipSrv
if /I (%1) == (mofcomp.exe) goto SkipSrv
%1 /RegServer

:SkipSrv
goto End

:TryInstall
if not exist wmicore.exe goto End
wmicore /s
net start winmgmt
:End

It will throw some errors. Ignore them. Then reboot the server.

Hack TwinUI to force Windows Store Apps run on low resolution screens

Windows Store Apps on Lumia 640 XL.

Windows 8 and Windows 8.1 has a minimum screen resolution constraint for Windows Store Apps (aka. Metro Apps or whatever). If the screen resolution doesn’t meet requirement, user will see a prompt indicating the resolution is too low for these applications.

However, on certain platforms (like phones and single-board computers), it is not convenient to change resolution. Recently I am trying Windows RT 8.1 on Lumia 640 XL. Qualcomm has the resolution hard-coded in platform configuration, so I was unable to change the resolution. 1280 * 720 is not sufficient for Store Apps.

But there was an exception – the PC settings (aka. Immersive Control Panel) app. It always opens regardless of current resolution settings. So how can I force other applications to launch?

Let’s turn to TwinUI.dll. It’s one of the core components of shell infrastructure. Start IDA Pro, load TwinUI with symbols from Microsoft. Go ahead and search the existence of PC settings app. All Windows Store Apps are associated with a package family identifier. Let’s search it. In this case, it’s windows.immersivecontrolpanel_cw5n1h2txyewy.

Bingo. We found it in some functions.

PC Settings Package Family ID is hardcoded in TwinUI.dll. This function has been patched by me, so it doesn't reflect actual situation you get from official Microsoft binary.
PC Settings Package Family ID is hardcoded in TwinUI.dll. This function has been patched by me, so it doesn’t reflect actual situation you get from official Microsoft binary.

By checking it’s references, we learned that layout checking routine verifies whether it is a desktop application, or PC settings app when resolution doesn’t meet requirements. Either you can patch layout checking routine or PC settings PFN verification routine. I decided to patch the second one, however patching the first is probably a better idea.

On ARMv7-A platform, I simply patched initial register store operation and the branch. Instruction BLX call was replaced with a simple NOP(MOV R0, R0).

Patched function
Patched function

There are two version of the PC settings check routines, so I need to patch both. The other one is similar to this one. Patching the layout verification routine (actually a better idea, as this patch will have some trouble when launch files from desktop) / patching on other architectures should be similar to this one.

A case that Hyper-V freezes host operating system

Two days ago I set up a new virtual machine for applications that require isolated security. When I put my computer into Connected Standby mode, I noticed SoC fan didn’t stop. To verify whether it was OS inconsistency or persistent issue, I manually initiated a system restart. However, it froze at login screen then. Nothing responded, including Ctrl + Alt + Delete key sequence. Attempting to force shutdown and start the computer almost didn’t improve the situation. After about ten attempts I managed to enter my desktop. There was no clue in event viewer: everything went well then suddenly the system froze.

I remembered that an alternative OS loader entry was configured to bypass Hypervisor launch at startup. I selected this entry to see whether it was related to Hyper-V. Test results indicated the freeze issue was strongly related to Hyper-V.

I tried to remember what I did before virtual machine configuration. I removed a virtual switch bridged to Surface Ethernet Adapter on my Surface Dock, then added a virtual switch bridged to VMware NAT adapter (which works better with Wireless network). Then I checked adapters in Network and Sharing Center, the old virtual switch didn’t get removed at all – and the “Remove” menu entry was unavailable. At last, I removed this adapter from Device Manager, and the issue was resolved.

This issue is likely related to OS inconsistency. When Hyper-V infrastructure attempts to initialize (bring up) all enabled network adapters including these Hyper-V virtual switches, the “removed” adapter is brought up, then enters failure state due to inconsistency in configuration. Because host operating system is a virtual machine on Hyper-V (with privileges), the host OS didn’t even get a chance to record what happened at that point.

The good thing is that I fixed it by myself; The bad thing is I missed an opportunity to report this bug and let Microsoft fix it.

Migrate legacy UWP project system to MSBuild-based

When Microsoft decided to adopt MSBuild on .NET Core platform, project.json was not dropped immediately until first toolchain RTM arrives. Dotnet Development on Universal Windows Platform Development leverages .NET Core too, but the depreciation progress is significantly slower than other .NET Core platforms due to historical reasons. UWP uses project.json for package management and MSBuild for builds.

In Visual Studio 2017 April Update, Microsoft finally migrates new UWP projects to full MSBuild-based project system. But our projects, which creates on early 2015, doesn’t get an auto migration as expected. Hence we decided to migrate them manually for additional benefits like better toolchain stability and advanced customization features.

Reminder: Do not attempt to use “dotnet migrate” CLI command, it won’t work for UWP projects.

Migration Prerequisites

  • Notify all your team members. Make sure everyone has Visual Studio 2017 with April update installed.
  • If you have continuous integration environment configured, make sure build agents have NuGet 4.1 or higher installed (3.5 or 4.0 won’t work).
  • Lock VCS during migration to prevent additional incidents. (We’re using TFVC for source management so that it will be easy)

Migration

  • Clean up all projects (including bin and obj directories)
  • Iterate all project directories
  • Find C# project file, open with your favorite editor.
  • Add following property group before project file lists:
<PropertyGroup>
    <RestoreProjectStyle>PackageReference</RestoreProjectStyle>
</PropertyGroup>

Okay, you’ve completed the first step. Then open your project.json file. Migrate all NuGet packages references as the picture below.

Package Reference
Package Reference

Finally, remove project.json and additional files like project.lock.json, *.nuget.targets, *.nuget.props. (Or your will get lots of warning that may lead .NET Native compilation fail)

Do it for every project. Then open Visual Studio, restore NuGet packages for all projects, build to validate and submit changes.

The Windows “Gatekeeper” Internals

"Rickrolling" in Windows SmartScreen

Windows 10 Insider Preview 15046 introduces the Windows-flavor “Gatekeeper“. It is similar to Gatekeeper in macOS, with some minor differences.

First of all, Windows “Gatekeeper” doesn’t block the execution of applications that don’t require installation. I tried to run PuTTY, a popular tool on Windows and it works.

Secondly, Windows “Gatekeeper” is based on Microsoft SmartScreen, which means disabling SmartScreen will turn it off too. Prior to application execution, SmartScreen will send file hash and publisher information(including certificate thumbprint) to Microsoft’s server, then SmartScreen server send back metadata including application reputation. Response is signed with a specific key that will be checked in client side for message integrity.

Unlike macOS, attempt to start application from console(e.g. Command Prompt and PowerShell) will trigger “Gatekeeper”.

Attempt to start application from PowerShell
Attempt to start application from PowerShell

The window is web-based. Although you can’t modify the response directly(no one wants to deal with sha256RSA unless the key leaks), you can attach a debugger to have some fun with it.

"Rickrolling" in Windows SmartScreen
“Rickrolling” in Windows SmartScreen

Microsoft claims that this feature is opt-in for most Windows SKUs (except Windows 10 Cloud AFAIK), and it is not revalent to UMCI (User-mode Code Integrity), which is enforced in Windows 10 Cloud.

Changing Microsoft Account alias is painful

Access deined for my new alias

A short update: The recent MSDN subscription migration kills my migrated account alias too. After contacting Microsoft support, I removed legacy alias from my account, create a new Microsoft Account using my legacy alias and restored my access to the new Visual Studio Subscription portal. In the same way, I removed legacy Microsoft Account in my Azure AD, linked two separated Microsoft Accounts(legacy and new alias) and resolved my issue accessing Visual Studio Team Services.

Such inconsistency always happens, and usually remove & add will be the universal solution in most cases.

After using legacy alias for almost 7 years, I decided to replace my Microsoft Account alias with a new Outlook.com email address due to increasing security concern of Netease Mail (my previous email service provider). Though I changed alternative recovery email to my domain email after several major security incidents, it looks weird to have an @163.com email alias linked to my Microsoft account.

Okay, I changed my alias the day before yesterday. It works. I didn’t delete the old one because I want to maintain some sort of backward compatibility. It works across my personal devices without any pain.

Annoying things came afterward days later.

Let’s talk about SSO/Federated Logon

Before talking about terrible things after switching to the new alias, let’s talk about Federated Logon. Technically speaking, Federated login is an authentication workflow based on trust relationships. Suppose Identity Provider A and Application B have successfully established two-way trust relationship by service provision. When a new user login attempt occurs, B redirects authentication challenges to Identity Provider A, with necessary metadata, like secure token ID, timestamp, nonce and finally something that validates the request, for example, digital signature, even token encryption. Since Application B has its own approach to understand Identity Provider A’s payload(so does B), the communication will be secured.

When Identity Provider A completes user authentication challenges(password, client certificate, fingerprint, etc.), it signs (encrypts maybe) authenticated user claims (user ID, user name and something else) and posts to B. The workflow image of WS-Federation below represents such workflow. OAuth and OpenID Connect have similar workflow with slight differences(multiple modes to retrieve user claims).

WS-Fed workflow from docs.oasis-open.org
WS-Fed workflow from docs.oasis-open.org

Microsoft Azure, Visual Studio Team Services and most Microsoft services use OpenID Connect. Believe it or not, you use Federated Logon and SSO every day.

Microsoft Account and Azure AD Account

They are two separated systems though they have something in common. Each Microsoft Account has a CID, a unique identifier in Microsoft Account system. All Microsoft Consumer services use CID to recognize your identity. For example, your Outlook.com email account is identified using your CID.

Azure AD Account handles it differently. Each Azure Active Directory have a tenant ID to identify AAD in AAD system. Each AAD contains objects: users, groups, computers, trust relationships….and more. Each AAD user has a unique alias in a specific AAD tenant. So the coexistence of 2ea6c0b4-cc49-42b8-9f1b-3f4aa653c719\imbushuo and b5093785-af31-4819-bf75-728d4474769c\imbushuo is possible.

Microsoft Accounts can be linked into Azure AD too: during the linking procedure, a new external user from Microsoft Account will be created in an AAD tenant, so you may have 2ea6c0b4-cc49-42b8-9f1b-3f4aa653c719\bill@live.com. When Bill wants to access resources in his tenant’s AAD, he will type bill@live.com in AAD Federation Service(Work and school account), a single sign on portal for Azure AD. Later, AAD FS will redirects the authentication challenges to Microsoft Account login portal. If Bill is authenticated in Microsoft Account login portal, he will be redirected back to AAD FS, with claims provided by Microsoft Account. Finally, AAD FS will tell the application that the user is Bill.

My blog uses such login mechanism too. See my management portal to get some idea about this if you don’t understand.

But…there’s no CID in Azure AD

But there’s something just works like CID: user alias. Another mapping! Microsoft Account will be mapped to Azure AD account, then the application will use the Azure AD account identity. After changing my alias in Microsoft Account, my Azure AD user alias remains the same. So I can login into my blog management portal with the same identity:

Logged in with the same ID
Logged in with the same ID

Do you remember that federation logon can carry multiple attributes at one time? So here’s the problem. My team’s source control service, Visual Studio Team Services, seems to use email address (which changes after rotating my primary Microsoft Account alias) to identity user. After logging in with my organization account, I found that my email address didn’t change after the rotation. To make the whole thing worse, I am the account creator, hence I cannot remove my Microsoft Account in VSTS to address the issue.

In short, the primary alias rotation didn’t change my user alias in Azure AD, but applications’ behavior vary based on how they deal with user claims.

 

Seems that I have to change my alias back. Yuck.

Using WASAPI Exclusive mode in Universal Windows Apps (Desktop)

Windows Audio Session API (WASAPI) was first introduced in Windows Vista. It offers advanced audio control and playback features for Windows Apps. Since it mitigates SRC issue in some aspects, WASAPI Exclusive Mode gains its popularity among music lovers. Windows Runtime supports a small subset of WASAPI APIs, including WASAPI Exclusive mode (in Windows 10).

However, here is one thing you should know: Windows 10 Mobile doesn’t support WASAPI Exclusive mode (by design).  As far as I know, only desktop platform is supported yet. Luckily, modern Windows Phone devices can choose the best format for shared mode using input wave’s format, so you don’t have to worry that (at least on Lumia 950 and Lumia 950 XL).

Audio Format

There’s no IMMDevice available in Windows Runtime. Try to create it via CLSID & IID will throw HRESULT Class Not Registered. It will cause some trouble getting all natively supported formats for Exclusive mode. A possible solution is using Properties property in DeviceInformation class in Windows Runtime instead of IMMDevice class & OpenPropertyStore method. Then, query the format using IsFormatSupported in IAudioClient2. Remember that in Exclusive Mode, system won’t return the best-fit wave format in this method, so you have to try all formats and select the best wave format by yourself. In my sample, I specified 44.1kHz / 16Bit / WaveFormat = 0x1, which is supported by my Surface Pro’s audio subsystem.

Initialize Audio Client

Then you can initialize IAudioClient2 in exclusive mode. Simply pass AUDCLNT_SHAREMODE_EXCLUSIVE in, specify Buffer Length and Wave Format. You may get some HRESULTs like AUDCLNT_E_BUFFER_SIZE_NOT_ALIGNED or AUDCLNT_E_BUFFER_SIZE_ERROR. Just check out this page and find solutions.

Perform Playback

Like HW-Offload mode, you don’t have to calculate available frames by yourself In event-based playback mode. The value for padding frames is exactly the same as available frames. Then return audio samples as what you do in shared mode.

Notes

It should supports Windows 8.1 desktop, but I haven’t test it on Windows 8.1 since I don’t have a Windows 8.1 desktop device.

I often noticed weird noise during playback when the system average load is high. I believe the root cause is process priority.

Windows 10 removed Background Audio category in WASAPI headers. In order to implement background playback, a customized out-of-process COM server or Media Foundation extension is required.

I don’t offer a demo program here, because it’s pretty easy to adapt the official sample to WASAPI Exclusive mode. 🙂

玩物丧志 · Yubikey 4 (智能卡登录)

Yubikey 是很早就有的东西了,然而受限于经济能力还有海关,直到最近有人提出来要团购我才买了个一个玩玩。我主要拿来做智能卡登录。

为什么呢?

虽然我用的电脑都装备有了 TPM ,但是这样还是有一些不方便的:

  • TPM 的数据基本上只留在这台电脑了(这也是优点)
  • 虽然我的电脑很轻,但是我不一定天天带出去,万一有事情需要连接到服务器上还是比较麻烦
  • 虚拟智能卡基本上一直在域账号里使用比较有效,然而我平时还是以登录个人账号为主(虽然电脑已经加入域)
 Yubikey 可以解决移动性的问题,而且出门不需要输入一个几十位复杂脑残的密码。
也许我哪天要玩玩 U2F 呢?这大概是以后的文章了。

准备智能卡证书

假定电脑已经加入域,域环境中已经部署了 Active Directory Certificate Services,并且 CS 服务器已经发布到 AD 中。

登录域账号,打开 Certificate Management,并 Request New Certificate。
一路往下,选择 Smart Card User / Smart Card  Logon 模板(我选的是前者)。
在 Private Key Configuration 下把私钥长度设置为 2048/4096,然后 CSP 不用动。
注:如果你选择了 Smart Card Crypto Service Provider,那么默认情况下在有 TPM 而且虚拟智能卡开启的情况下,会选择的是虚拟智能卡,在 Windows 证书选择里表示为“安全设备凭据”而不是“智能卡凭据”,但是功能类似。然后勾选允许导出私钥。
申请完证书,导出证书。
打开 Yubikey PIV Manager,并导入证书。

Screenshot of Yubikey PIV Manager
Screenshot of Yubikey PIV Manager

基本工作到此结束。下面来试试智能卡登录。

如果是要给 Active Directory Federation Services 打开智能卡登录支持呢?

很简单。进入 AD CS 管理界面,找到认证选项,在对应的 Intranet / External 认证模式里勾选证书登录,AD FS Web Proxy 启用49443端口即可。

Smartcard and ADFS
Smartcard and ADFS

效果大概如图所示。

未完待续