0

I am writing a python script on an Ubuntu server that calls an API to conduct some operations. To call this API requires a Bearer token provided by the service. I tried to hide the token by only making the script executable but not readable. This did not work as the python runtime needs to read the script to execute it as well.

Is there any way I can protect the API key from being viewed by a regular Linux user but still allow them to run the script?

Background: I am using the trap command to detect when a user runs npm start. When detected, the script will run and conduct the necessary operations.

Here is the script I am running:

#!/usr/bin/env python3

import requests
import json

HEADERS = {
  'Authorization': f'Bearer {API_KEY}',
  'Content-Type': 'application/json'
}

def get_info():
  GET_CONFIG_LINK = 'INSERT_URL_HERE'
  get_response = requests.get(GET_CONFIG_LINK, headers=HEADERS)
  get_response_STATUS = get_response.status_code
  
  if not get_response.ok:
    return {}

  get_response_JSON = get_response.json()
  return get_response_JSON

print(get_info())

How it is run:

#! /bin/bash

command_to_monitor='npm start'

function trap_command(){
  if [ "$BASH_COMMAND" == "$command_to_monitor" ]; then
    actionResult=$(cd /usr/local/bin; ./action.py)
    echo "action completed"
  fi
}

trap 'trap_command' DEBUG

I tried using chmod 711 on the script to remove read access from the user. That did not work as python cannot run without reading the script.

I tried moving the API_KEY to an env variable. However, every user will have different env variables.

I also tried passing it in as a flagged variable. But the script is ran from the /etc/profile which is readable by all users. So there is no difference.

Thinking of translating it to use C so it can be a binary executable. However, this solution seems a little too troublesome. Hence would prefer if there is something simpler.

  • Whatever information you store on the user's computer, the user can see. Encryption will not work for this sort of application, because *your program must be able to decrypt the stored data in order to use it*; a user who has access to your source code, can write a new program based off of it, to decrypt the stored data and display it. (Please look up the history of DeCSS.) But this shouldn't be a problem because *each user should have a separate API key anyway*. Ideally, it would be the user's responsibility to generate one, or else your program would request one during installation. – Karl Knechtel Feb 02 '23 at 03:03
  • But in terms of how to store the information, please see the linked duplicate. – Karl Knechtel Feb 02 '23 at 03:03

0 Answers0