0

I'm writing a CLI using python that pretty much is wrapping around an API for a website. There is authentication for the API, so I need to ask the user for their username and password. I'm not sure how to store these on the system without having them saved in plaintext somewhere. Is there a best practice for something like this?

As an example, a user might call from the command line:

python some_cli.py

And this will prompt them for their username and password if it isn't already saved. I thought about trying to save them with os.putenv or os.environ, but that won't be saved since this process will die and these won't be saved for future processes. The only thing I can think of is to have a file that this information will be saved in and read from.

TheStrangeQuark
  • 2,257
  • 5
  • 31
  • 58

2 Answers2

3

Use the credentials the user enters to log into the web API that you are wrapping. The API should return a token or a session, just as if you were using it in the browser. Store this token or session somewhere in your CLI program as a variable or store this in a file. This will need to remain as plaintext. Each CLI instance can use this file to make requests to the API when run. You will need to handle expired sessions/tokens too by asking the user for their credentials to re-authenticate.

labennett
  • 317
  • 1
  • 5
0

Generally, passwords are salted and hashed before they are stored on the system's hard disk. It sounds to me as though you're writing a client-side password storage script. Therefore, I would recommend the SHA-2 or bcrypt hashing algorithms to make your passwords unintelligible before storing them. Do not use MD5 or SHA-1 to hash your passwords, as they have known vulnerabilities.

When the user-supplied password and the real password is compared, they are not compared in plaintext. The user-supplied password is first salted, then hashed. The resulting hash is compared with the hash of the "correct" password that is stored on the disk. Using this method, the plaintext password is never stored on the disk. Additionally, since the probability that two hashes will match is extraordinarily low, it is considered a safer practice than storing plaintext passwords (a much, much safer practice because hashes are extremely difficult to reverse even if the attacker knows the hash).

This thread has a couple of interesting implementations of salting and hashing, including a bcrypt implementation. Salt and hash a password in python

A secure password storage tutorial may help you on your journey.

Keep in mind that cryptography has its weaknesses. Rainbow table attacks, timing attacks, and known plaintext attacks are all things that must be understood when switching to cryptographic password storage. That being said, cryptography is a highly respected field known to offer good security.

I'd recommend you join Stack Exchange's Cryptography Forum

armitus
  • 712
  • 5
  • 20