In this post I will be explaining how to leverage PowerShell to create a time-based one-time password (TOTP). If you are not familiar with the concept of one-time passwords, the key point is that they are passwords that can be used only (drum roll) one time. If you require more information please see this Wikipedia article. If you have ever used RSA’s SecurID or Google’s Authenticator app, you are using a one-time password, and a time-based one at that.

We encountered a situation where we wanted to have the ability to create a TOTP using PowerShell. I assumed that there would have been a library or module available already but didn’t find one after a few quick searches, so I decided to look into writing a script from scratch. Disclaimer: I am not much of a coder in any language (least of all PowerShell), so hate tweets are welcome. Being somewhat familiar with Python, I decided to try to use this Python module as a starting point. However, I left several features out due to lack on necessity for our purposes. I also had to take a look at the RFC which was interesting as it is the first one that I have ever had to read deeply into a security concept. After getting comfortable with the concepts, finishing the research, and receiving a lot of help from steiner, I came up with the following:

(Side note: I had originally planned to turn this into a fully featured PowerShell module, but other things took precedence, and I haven’t spent much time with it lately.)

While there isn’t anything particularly groundbreaking here, it is now relatively simple to generate a TOTP on a Windows system without installing any third party programs. You don’t even have to write the script to disk if you use PowerShell’s “Invoke-Expression” cmdlet as follows:

Since TOTPs are typically used in authentication, you may be wondering what an attacker would want with something like this. This would probably be useful in exfiltrating data after a successful breach. This would give the client (infected system) the ability to encrypt data by taking a dynamically generated value which could be then combined with a known value, such as the hostname. Hash these values and use the result as a key to encrypt data before transmission to a server (attacker system). The server could then calculate the TOTP, or several possibilities based on the time the data was received, and decrypt the information with relative ease. Additionally, it can still be used with authentication in malware, the possibilities are really only limited by one’s imagination. The following image shows both the Python and PowerShell implementations generating the same TOTP.

Generating a TOTP in Python and PowerShell

It should be noted that the Python implementation requires the shared secret to be base32 encoded while the PowerShell requires base64.