Install Check Point Firewall Policy through API using Telegram

Automation continues to grow amongst all information technology verticals; security is no exception.  As the world continues to evolve, so must we.  Users are looking for the easiest functionality with the most security.  Using and understanding the API, this can be achieved.

Here is a simple example how to install the threat prevention firewall policy to one gateway through a basic Telegram - Bot interaction.

Prerequisites:

Steps:

If desired, download for bot.py and token_file.py source code is available here

Create New Bot on Telegram

Start a conversation with @BotFather

The Botfather!

Send @BotFather the command /newbot

Follow the conversation.

Once the conversation is complete, you will have a Telegram API Token for your bot.

Sample message received when a new bot is created

Keep record of both the bot user name and token, as this is how you will be communicating with the bot.

Create token_file.py or other authentication

Please Note:
token_file.py is a clear text file with tokens, IPs, users and passwords in this demonstration.  It is recommended that other methods of authentication be used to increase security.

Create a token_file.py file

Create variables for the following information:
telegram_token, mgmt_ip, mgmt_user, mgmt_password, mgmt_target_gateway, mgmt_policy

telegram_token="14072342828:AAG4YgkCasdfSDfjaksGSwoWORK"
mgmt_ip="192.168.1.1"
mgmt_user="admin"
mgmt_password="admin"
mgmt_policy="Standard"
mgmt_target_gateway="gw-1"
token_file.py example

The token_file.py should look similar (using your own parameters) to the one listed above.

Create bot.py and import necessarily libraries

Assign the correct bin location and import the correct libraries. Import the libraries from the screenshot: logging, cpapi, telegram, telegram.ext and token_file.

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import logging

from cpapi import APIClient, APIClientArgs

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

# token_file parameters
# these variables are imported from another file - this is for demo purposes
from token_file import telegram_token, mgmt_ip, mgmt_user, mgmt_password, mgmt_target_gateway, mgmt_policy
importing the required libraries and variables

Enable Basic Logging

Enable basic logging by building out the function below.

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

logger = logging.getLogger( __name__ )

Build the Telegram command functions

The bot is designed to accept three commands: /start , /help and /install.

/start and /help are commands that simply generate a reply text to the user on Telegram.

/install calls the install_policy function and returns a response based on the output of that function. The install_policy will be built in the next section.

Below is an example the functions.

def start(update: Update, context: CallbackContext) -> None:
    # Message issues when bot is started.
    update.message.reply_text("Welcome to FirewallBot!\nPlease issue the below commands:\n/install - install standard policy on gateway")

def help(update: Update, context: CallbackContext) -> None:
    # Help message for users to enter.
    update.message.reply_text("Please issue the below commands:\n/install - install standard policy on gateway");

def install(update: Update, context: CallbackContext) -> None:
    # Install command for users to enter
    success_message = install_policy();
    update.message.reply_text(success_message);

Building the install_policy function

APIClientArgs and APIClient details can be found in the cpapi repository.  Different parameters can be accepted such as login via API key (version 1.7+)

The client_args variable is built on the APIClientArgs function (from the cpapi library) accepting the connection details for the management server.

Using the APIClient function (again from the cpapi library), the client_args variable is based through and utilized as the client variable.  This is where the login_res comes in.  By calling the client.login function passing the username and password (or API key in newer versions, as pointed out earlier) the login_res will receive a data parameter in “success”.

An “if / else” statement is created.  If the login result was unsuccessful, (login_res.success is False) a message stating that the login has failed will be sent to the user.

The “else” statement means the login was successful and the next objective is to install the policy.  In a similar fashion, if the api_res is successful a message will be sent to the user stating so. In every other event, a failure message will be sent to the user.

The message will then be returned depending on the outcome.

# install_policy function that calls check point mgmt api
def install_policy():

    client_args = APIClientArgs(server=mgmt_ip, port=4434, api_version=1.5)
    message = ""

    with APIClient(client_args) as client:

        login_res = client.login(username=mgmt_user,password=mgmt_password)
        if login_res.success is False:
            message = "Login failed: {}".format(login_res.error_message)
            print(login_res)

        else:
            api_res = client.api_call("install-policy", {"policy-package":mgmt_policy, "targets":mgmt_target_gateway, "access":0, "threat-prevention":1})

            if api_res.success:
                message = "Policy installed successfully!"

            else:
                message = "Policy was UNABLE to be installed :("

    return message

Build out the main function

Now, connect the dispatcher, add the handles and start polling the bot.

def main():

    # Prepare credentials for mgmt_api
    # Should be done via secure entry, not hard coded text file.

    # Start Bot.
    updater = Updater(telegram_token, use_context=True)

    # dispatcher to register handlers
    dispatcher = updater.dispatcher

    # commands in Telegram
    dispatcher.add_handler(CommandHandler("start", start))
    dispatcher.add_handler(CommandHandler("install", install))
    dispatcher.add_handler(CommandHandler("help", help))

    # Start Bot
    updater.start_polling()

    updater.idle()

if __name__ == ' __main__':
    main()

Conclusion

Execute the bot.py file by typing “python3 bot.py”.  You will then have an active script running in your command line or terminal.

It should have similar functionality to the preview image.

If you do run into any issues please feel free to reach out!  Check out the repository, send an email to me @ seanland.ca or simple send me a message through one of my socials on the main page!