Using Commander With AWS Lambda

Run Commander in the AWS Cloud

About

Commander is a powerful tool that can solve many issues and provide valuable information about your Keeper Security environment. In addition to using Commander on a local desktop or server, Commander can be run in a cloud environment such as AWS for performing scheduled or on-demand requirements.

In this example, we will demonstrate how to use Commander with AWS Lambda to run user and usage reports on a scheduled basis.

Prerequisites

  • Commander

  • A Keeper user account with a Master Password login method (SSO login and MFA will not work without human interaction)

  • Access to AWS and permissions to create Lambda functions, and create layers in AWS Cloud9

Steps

Create a Lambda Layer With Cloud9

Commander needs to be packaged on a machine that matches what it will run on in AWS Lambda. to do this, we can create the Commander package in Cloud9.

Select Amazon Linux 2 as Cloud9 platform.

In AWS Cloud9 check the version of installed Python interpreter.

python3 --version
Python 3.7.16

As of March 2023, you can install Python3.8

sudo amazon-linux-extras install python3.8

python3.8 --version
Python 3.8.16

In AWS Cloud9, create a layer via the zip file method and add a python directory

mkdir commander-layer
cd commander-layer
mkdir python

Use pip to install the following dependencies:

  • keepercommander

pip3 install -t ./package keepercommander

if Python3.8 was installed

pip3.8 install -t ./package keepercommander

Zip the now installed Commander package

zip ../deployment-package.zip .
cd ..

Publish the Lambda layer

aws lambda publish-layer-version --layer-name keepercommander 
--zip-file fileb://deployment-package.zip --compatible-runtimes python3.7
aws lambda publish-layer-version --layer-name keepercommander 
--zip-file fileb://deployment-package.zip --compatible-runtimes python3.8

Create a Lambda

In AWS Lambda, use the Lambda editor to write a Python function.

The lambda_handler function is triggered by Lambda when it is processed.

See a complete example of a Commander Lambda function below:

#  _  __
# | |/ /___ ___ _ __  ___ _ _ ®
# | ' </ -_) -_) '_ \/ -_) '_|
# |_|\_\___\___| .__/\___|_|
#              |_|
#
# Keeper Commander
# Copyright 2023 Keeper Security Inc.
# Contact: ops@keepersecurity.com
#
#
import json
import os
import datetime
from typing import Optional

from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

import boto3

from keepercommander import api
from keepercommander.commands.enterprise import UserReportCommand, SecurityAuditReportCommand
from keepercommander.params import KeeperParams

# Create report (format: JSON) combining data from 2 existing Commander reports
def create_user_report(params):  # type: (KeeperParams) -> Optional[str]
    user_report = UserReportCommand()
    user_report_data = user_report.execute(params, format='json')
    data = json.loads(user_report_data)
    users = {x['email']: x for x in data}
    security_audit_report = SecurityAuditReportCommand()
    security_audit_report_data = security_audit_report.execute(params, format='json')
    if security_audit_report_data:
        data = json.loads(security_audit_report_data)
        for x in data:
            if 'email' in x:
                email = x['email']
                if email in users:
                    user = users[email]
                    for key in x:
                        if key not in user:
                            if key not in ('node_path', 'username'):
                                user[key] = x[key]
                else:
                    users[email] = x

    return json.dumps(list(users.values()), indent=2)


# This Lambda's entry point
def lambda_handler(event, context):
    params = get_params()
    api.login(params)
    
    # Log Commander-related issues (e.g., incorrect credentials, improper account privileges) using AWS's built-in logging module and abort
    if not params.session_token:
        print('Not connected') 
        return 'Error: See Lambda log for details'
    if not params.enterprise:
        print('Not enterprise administrator')
        return 'Error: See Lambda log for details'
    
    # Generate and send report 
    report = create_user_report(params)
    response = email_result(report)
    return response


# Email report data (as JSON attachment) to recipient specified in this Lambda's environment variables
def email_result(report):
    sender = os.environ.get('KEEPER_SENDER')
    sendto = os.environ.get('KEEPER_SENDTO')
    region = 'us-east-1'
    ses_client = boto3.client('ses', region_name=region)

    message = MIMEMultipart('mixed')
    message['Subject'] = 'Keeper Commander User Security Report With  CSV (attached)'
    message['From'] = sender
    message['To'] = sendto
    now = datetime.datetime.now()

    body = MIMEText(f'User Report Output created and sent at {now}', 'plain')
    message.attach(body)

    attachment = MIMEApplication(report)
    attachment.add_header('Content-Disposition', 'attachment', filename='user-report.json')
    message.attach(attachment)

    response = ses_client.send_raw_email(
        Source=message['From'],
        Destinations=[sendto],
        RawMessage={'Data': message.as_string()}
    )
    
    return response


# Get required Commander parameters from environment variables
def get_params():
    user = os.environ.get('KEEPER_USER')
    pw = os.environ.get('KEEPER_PASSWORD')
    server = os.environ.get('KEEPER_SERVER')
    private_key = os.environ.get('KEEPER_PRIVATE_KEY')
    token = os.environ.get('KEEPER_DEV_TOKEN')
    my_params = KeeperParams()
    my_params.user = user
    my_params.password = pw
    my_params.server = server
    my_params.device_private_key = private_key
    my_params.device_token = token
    return my_params


if __name__ == '__main__':
    from keepercommander.__main__ import get_params_from_config
    my_params = get_params_from_config(os.path.join(os.path.dirname(__file__), 'config.json'))

    if my_params.user:
        print(f'User(Email): {my_params.user}')
    else:
        while not my_params.user:
            my_params.user = input('User(Email): ')

    api.login(my_params)
    if not my_params.session_token:
        exit(1)

    print(create_user_report(my_params))

The function is made up of several parts:

The lamda_handler function

This function is called when the lambda is triggered, all other functions should be called from this one.

Gathering Commander Parameters

Commander uses some parameters in order to authenticate the user account. We will attach these as environment variables and inject them into the Lambda. See further instructions below.

Commander Functions

The above steps are all that are required to run Commander in Lambda, once they have been done and Commander SDK code can be performed.

In this example, we run a user status report and send the results to an email address.

Setting Commander Parameters

Commander uses some parameters to authenticate the user account and identify what Keeper region to access. In order to pass these parameters into Lambda, we will set them as environment variables.

Gathering parameters

Commander automatically creates the required parameters when you login to the CLI. The easiest way to generate the required parameters is to login to the Commander CLI on your machine.

To get the Commander parameters, open the generated config.json file. By default this is located in the Users/[your username]/.keeper/ folder on your machine. See the config file documentation for more information.

You should see a file that looks similar to this:

{
    "clone_code": "36[...]A0g",
    "user": "user@example.com",
    "server": "keepersecurity.com",
    "private_key": "sxv[...]oz3p=fzw",
    "device_token": "xko[...]r2IxdiQ"
}

Setting Parameters in AWS Lambda

To set the required Commander parameters as environment variables, first head to the lambda configuration and select "Environment Variables".

Set each commander parameter as an environment variable to be used by the Lambda.

You will also need to add your keeper master password to be used to login to Commander.

Environment Variable NameValueExample

KEEPER_USER

Keeper user account email address (config user field)

user@example.com

KEEPER_SERVER

Keeper server domain (config server field)

keepersecurity.com

KEEPER_CLONE_CODE

clone_code field from config

36df3[...]A0dsa4g

KEEPER_PRIVATE_KEY

private_key field from config

sxv[...]oz3p=fzw

KEEPER_DEV_TOKEN

device_token field from config

xko[...]r2IxdiQ

KEEPER_PASSWORD

Password for keeper account

*****

KEEPER_SENDER

Email address to send emails from

user@example.com

KEEPER_SENDTO

Email address to send emails to

receiver@example.com

We are using environment variables to set the email addresses to send from and to for this example code. If you are not sending an email in your script, these are not needed

Configure Lambda

Set Timeout

In the general configuration section of the Lambda configuration, it is recommended to change the timeout value. Some Commander functions take time, so if your script takes longer to complete than this number, the Lambda will automatically end without finishing.

You can set this to any number you are comfortable with. A value of 300 seconds (5 minutes) should be more than enough time for most processes.

Select Layer

In the Lambda editor, select the layer that you created above to include the Commander package in your Lambda build.

Create run Schedule

Create an EventCloud trigger to trigger the Lambda and set it to trigger at a cadence of your choice (for example once per day, or once every 30 days).

AWS can also be configured to trigger Lambda from a number of other sources including email and SMS triggers. See Amazon's documentation on invoking Lambda for more options:

Configure For Sending Emails

In this example, we are sending an email with the report results. In order to enable the email, you will need to allow Lambda to access SES SendEmail/SendRawEmail service.

You will also need to create an IAM identity to enable email sending.

For more information on setting up email sending with AWS, see Amazon's documentation:

In this example, we are sending an email with the report results. In order to enable the email, you will need to allow Lambda to access SES SendEmail/SendRawEmail service.

Next Steps

In this example, we run a report that combines the results of 2 Commander reports (security-report and security-audit-report) and send it via email as a JSON attachment, allowing us to obtain enterprise-wide security-monitoring data -- e.g., last-login date and overall security scores for each user in the enterprise -- in a regularly-scheduled and automated way. However, with this setup, any other set of Commander functions can be run with Lambda.

Experiment with other Commander functionality, Lambda invocation methods, and other AWS services (such as SNS for utilizing various methods for push notifications -- including SMS messages) to bring automated value to your Keeper processes.

For some examples of using the Commander SDK code, see the example scripts in the Commander GitHub repo:

To learn more about Commander's various methods, see the Command Reference section.

Command Reference

Last updated