Using GnuPG to Handle Your Network Automation Credentials!

One thing I struggled a long time with is the following:

How do we code our network while securely handling our device credentials? How do we do this in a way that is highly collaborative?

Here’s one issue that I ran into. It is easy to get roped into baking your credentials into a script (completely guilty here). But what happens when it’s time to deliver your code to a colleague, or even an external customer? You will need to refactor your code to deal with the AAA credentials that are displayed (plaintext) in your code.

With python and GnuPG, we can securely deal with device credentials in sharable code.

One of my favorite parts about this strategy is thinking about the extensibility of GnuPG….particularly with its ability send and receive secure messages. This post won’t dive into that much. Instead we’ll stick to the following objectives:

  1. Install GnuPG, the associated python libraries, and generate keys.
  2. Build an encrypted credentials file in yaml or json.
  3. Use python to interface with your keys and securely load your credentials.

Ok… that was highly summarized..let’s get into the details:

Installing gpg via brew…there is more chatter in real life, but this is a blog:

Installing the required python libraries.

 

Generating keys…Please read the entire section before starting.

This step generates a public and private key, in the .gnupg folder. When you proceed to using this in code, you encrypt with the specified users public key, and decrypt with your own private key.

Run this command and follow the self explanatory prompts. Be advised that not generating a passphrase is less secure. In this scenario I’m treating my keys like ssh rsa keys and giving them file permissions of 600.

 

Cool…lets play with gnupg in the interpreter:

We specify our .gnupg location and begin to interact with our keys:

Lets encrypt some stuff. We setup a string to encrypt and perform the encryption with the gpg.encrypt() function. We also have ways to make sure the encryption worked, and see the encrypted object.

Yes this is an object!

That means you have to convert to a string with the str() function to decrypt it…you guessed it, that’s next:

 

Ok, we have gnupg working in python and bash. How do we automate our network credentials?

First we need to encrypt credentials_file.txt from bash:
Here is the credentials file:

Here’s how we encrypt it.

 

And here is our python…we made it!

There might be a lot to look at below, but look at the “Decrypt/Load credentials” section. We’re automating our network credentials securely! The creds are loaded and used by the connection handler…in code that’s shareable.

This script deploys a new vlan to a datacenter ethernet fabric, and ensures the new vlan is available via 802.1q tag to a pre-specified Vmware cluster.

Leave a Reply