Create Telegram Bot to Generate MFA RSA SecurID Software Token

I write this post to create a Telegram chatbot that can generate a token for Check Point Mobile VPN. Each time I need to login into a VPN account, I need to supply a token generated by RSA SecurID. The RSA SecurID Software Token is bound to a Device Serial Number on each installation on a specific device. Since we only have one person have one token RSA SecurID registered. Each time we need to connect to VPN, we need to contact him to get VPN token access. So I like to have automated.

So I build it with python. The first thing is installing stoken and load the sdtid without password, then python3 and pip3:

sudo apt install python3 pip3

Then download the python-telegram-bot:

pip3 install python-telegram-bot

First I made the function to generate token by execute stoken command:

from subprocess import check_output

def generate_token(pin="0000"):
    '''
    Returns token generated from stoken.
            Parameters:
                    pin (str): pin for token code
            Returns:
                    token (str): generated token from stoken
    '''
    # Execute command stoken tokencode --pin=pin
    # decode from byte to string UTF-8, and strip \n from from stoken result
    token = check_output(["stoken","tokencode","--pin=" + pin]).decode("utf-8").rstrip('\n')
    # return the genereated token
    return token

And save it as token_generator.py. Then make another script to call telegram bot:

import logging

from telegram.ext import Updater, CommandHandler, MessageHandler, Filters

from token_generator import generate_token

# Enable logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
                    level=logging.INFO)

logger = logging.getLogger(__name__)

# Define a few command handlers. These usually take the two arguments update and
# context. Error handlers also receive the raised TelegramError object in error.
def start(update, context):
    """Send a message when the command /start is issued."""
    update.message.reply_text('Please use /token to request token.')

def send_token(update, context):
    """Send a message when the command /token is issued."""
    # Set user pin for stoken
    user_pin = "000000"
    # Pass pin to generate_token and return token result
    generated_token = generate_token(pin=user_pin)
    # Build token message
    message = "Your token is: " + generated_token + "."
    # Send token
    update.message.reply_text(message)

def error(update, context):
    """Log Errors caused by Updates."""
    logger.warning('Update "%s" caused error "%s"', update, context.error)

def main():
    """Start the bot."""
    # Create the Updater and pass it your bot's token.
    # Make sure to set use_context=True to use the new context based callbacks
    # Post version 12 this will no longer be necessary
    # Put the telegram bot token here
    updater = Updater("123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11", use_context=True)

    # Get the dispatcher to register handlers
    dp = updater.dispatcher

    # on different commands - answer in Telegram
    # command answer for /start
    dp.add_handler(CommandHandler("start", start))
    # command answer for /token
    dp.add_handler(CommandHandler("token", send_token))

    # log all errors
    dp.add_error_handler(error)

    # Start the Bot
    updater.start_polling()

    # Run the bot until you press Ctrl-C or the process receives SIGINT,
    # SIGTERM or SIGABRT. This should be used most of the time, since
    # start_polling() is non-blocking and will stop the bot gracefully.
    updater.idle()

if __name__ == '__main__':
    main()

Make sure add shebang on each script:

#!/usr/bin/env python3

then make the files executable with command:

chmod +x token_bot.py token_generator.py

Execute the script with command:

./token_bot.py

You can make it run on background by add & behind the command:

./token_bot.py &

Result of script execution

Result of script execution
Result of script execution

Result of token bot:

Result of token bot on Telegram
Result of token bot on Telegram

The source code can be downloaded on my Github.