Sample to identify login and logout operations from invalid IP addresses

This function analyzes received operation records, filters logins or logouts from unauthorized IP addresses using a whitelist, and sends alarms under a specified SMN topic.

This function can be used to build an account security monitoring service.

Prerequisites

Before running this example, ensure you have the following:

FunctionGraph function

cts-login-check/src/index.py
import ipaddress

import requests


# Handler for CTS login/logout events and IP whitelist checking.
def handler(event, context):
    logger = context.getLogger()

    logger.debug("event: %s", event)

    ctsmsg = event["cts"]

    # Resource operator IP
    SOURCE_IP = ctsmsg["source_ip"]
    # trace_name
    ACTION = ctsmsg["trace_name"]

    IP_RANGES_WHITELIST = context.getUserData("IP_RANGES_WHITELIST")

    if not IP_RANGES_WHITELIST:
        return "IP_RANGES_WHITELIST is not configured, fail"

    if ACTION not in ("login", "logout"):
        return f"Action {ACTION} is not valid, fail"

    body = {
        "subject": f"CTSTrigger: Illegal {ACTION} from non-whitelisted IP",
        "message": f"Illegal operation [{ACTION}] from [{SOURCE_IP}], user [{ctsmsg['user']['name']}]",
    }

    # Check if source IP is in the whitelist
    for ip_range in IP_RANGES_WHITELIST.split(","):
        try:
            if ipaddress.ip_address(SOURCE_IP) in ipaddress.ip_network(
                ip_range.strip(), strict=False
            ):
                return f"Reasonable {ACTION} from IP {SOURCE_IP}"
        except ValueError:
            logger.error(f"Invalid IP range: {ip_range}")
            body = {
                "subject": "Configuration Error",
                "message": f"CTSTrigger: Invalid IP range {ip_range} configured in IP_RANGES_WHITELIST: {IP_RANGES_WHITELIST}",
            }
            break

    return send_alarm_message(context, body)


# Send an alarm message to the specified SMN topic using the provided context and message body.
# Reference: https://docs.otc.t-systems.com/simple-message-notification/api-ref/apis/message_publishing/publishing_messages_in_the_text_format.html
def send_alarm_message(context, body: dict) -> str:
    logger = context.getLogger()

    SMN_ENDPOINT = context.getUserData("SMN_ENDPOINT")
    SMN_TOPIC_URN = context.getUserData("SMN_TOPIC_URN")
    PROJECT_ID = context.getProjectID()
    TOKEN = context.getToken()

    logger.info(
        f"Sending alarm message to SMN topic {SMN_TOPIC_URN} at endpoint {SMN_ENDPOINT}"
    )

    headers = {"X-Auth-Token": TOKEN, "accept": "application/json"}

    url = f"https://{SMN_ENDPOINT}/v2/{PROJECT_ID}/notifications/topics/{SMN_TOPIC_URN}/publish"

    return_value = None
    try:
        response = requests.post(url, headers=headers, json=body, timeout=10)
        if response.status_code != 200:
            logger.error(
                f"Failed to send alarm message, status code: {response.status_code}"
            )
            return_value = "Send alarm message failed."
        else:
            return_value = "Send alarm message success." 

    except requests.exceptions.RequestException as error:
        logger.error(f"Failed to send alarm message: {error}")
        return_value = "Send alarm message failed."

    return return_value

Environment variable

Sample value

Description

SMN_TOPIC_URN

urn:smn:eu-de:1234567890:my-topic

The SMN topic to send alarms to.

SMN_ENDPOINT

smn.eu-de.otc.t-systems.com

The SMN endpoint to send alarms to.

IP_RANGES_WHITELIST

10.0.0.1/28

Comma separated list of IP ranges that are allowed to access the system.

Terraform deployment files

Terraform config files

cts-login-check/terraform/variables.tf
# prefix will be prepended to all resource names
variable "prefix" {
  type    = string
  description = "set in variables.tfvars"
}

# description of the function
variable "description" {
  type    = string
  description = "set in variables.tfvars"
}

# FunctionGraph: Function name
variable "function_name" {
  type    = string
  description = "set in variables.tfvars"
}

variable "handler_name" {
  type    = string
  description = "set in variables.tfvars"
}

# Resource tag:
variable "tag_app_group" {
  type    = string
  description = "set in variables.tfvars"
}

variable "SMN_ENDPOINT" {
  type    = string
  description = "set in variables.tfvars"
}

variable "SMN_EMAIL_ADDRESS" {
  type    = set(string)
  description = "set in variables.auto.tfvars"
}

variable "IP_RANGES_WHITELIST" {
  type    = set(string)
  description = "set in variables.auto.tfvars"
}

variable "TEST_USER_NAME" {
  type    = string
  description = "set in variables.auto.tfvars"
}

variable "TEST_USER_ID" {
  type    = string
  description = "set in variables.auto.tfvars"
}

variable "TEST_ALLOWED_SOURCE_IP" {
  type    = string
  description = "set in variables.auto.tfvars"
}
variable "TEST_DENIED_SOURCE_IP" {
  type    = string
  description = "set in variables.auto.tfvars"
}

FunctionGraph deployment files

cts-login-check/terraform/function.tf
##########################################################
# Python event function to handle CTS event
##########################################################
resource "opentelekomcloud_fgs_function_v2" "MyFunction" {

  name   = format("%s_%s", var.prefix, var.function_name)
  app    = "default"
  
  handler =  var.handler_name

  runtime   = "Python3.10"

  agency = opentelekomcloud_identity_agency_v3.agency.name  

  code_type = "inline"
  func_code     = filebase64(format("${path.module}/../%s", "src/index.py"))
  code_filename = "index.py"

  description      = var.description
  memory_size      = 128
  timeout          = 30
  max_instance_num = 10

  log_group_id   = opentelekomcloud_lts_group_v2.MyLogGroup.id
  log_group_name = opentelekomcloud_lts_group_v2.MyLogGroup.group_name

  log_topic_id   = opentelekomcloud_lts_stream_v2.MyLogStream.id
  log_topic_name = opentelekomcloud_lts_stream_v2.MyLogStream.stream_name

  # set some environment variables
  user_data = jsonencode({
    "SMN_TOPIC_URN" : opentelekomcloud_smn_topic_v2.topic_1.topic_urn,
    "SMN_ENDPOINT" : var.SMN_ENDPOINT,
    "IP_RANGES_WHITELIST" : join(",", var.IP_RANGES_WHITELIST)
  })

  tags = {
    "app_group" = var.tag_app_group
  }

}

output "MY_FUNCTION_URN" {
  value = opentelekomcloud_fgs_function_v2.MyFunction.urn
}

output "MY_FUNCTION_VERSION" {
  value = opentelekomcloud_fgs_function_v2.MyFunction.version
}

SMN deployment files

cts-login-check/terraform/smn.tf
# Create an SMN topic and subscriptions for the FunctionGraph function

# Create an SMN topic for the FunctionGraph function
resource "opentelekomcloud_smn_topic_v2" "topic_1" {
  name         = format("%s_%s_topic_1", var.prefix, var.function_name)
  display_name = format("Message from FG function: %s", var.function_name)

  tags = {
    "app_group" = var.tag_app_group
  }
}

# Create SMN subscriptions for each email address in the list
resource "opentelekomcloud_smn_subscription_v2" "subscriptions" {
  for_each = var.SMN_EMAIL_ADDRESS
  endpoint  = each.value
  topic_urn = opentelekomcloud_smn_topic_v2.topic_1.topic_urn
  protocol  = "email"  
  remark = format("Subscription for %s", var.function_name)  
}

Variables

Sample variables file:

cts-login-check/terraform/variables.tfvars
# Terraform variables for scratch-event sample

# prefix of all resources
prefix        = "python"

# description of the function
description = "Custom rule for CTS login check"

# name of the function (will be prefixed)
function_name = "fg-cts-login"

# handler function name defined in your code, e.g. "index.handler"
handler_name = "index.handler"

# resources will be tagged with this app_group tag
tag_app_group = "fg-cts-login"

SMN_ENDPOINT = "smn.eu-de.otc.t-systems.com"

You might want to adjust the variables to your need.

Makefile

Sample Makefile:

cts-login-check/Makefile
# Makefile for Terraform deployment
SHELL := /bin/bash

# Terraform backend configuration
BACKEND_CONFIG_BUCKET := "doc-samples-tf-backend"
BACKEND_CONFIG_KEY := "terraform_state/python/fg-cts-login.tf"
BACKEND_CONFIG_REGION := "eu-de"
BACKEND_CONFIG_ENDPOINTS := "endpoints={s3=\"https://obs.eu-de.otc.t-systems.com\"}"

CURRENT_MAKEFILE := $(firstword $(MAKEFILE_LIST))

# IAC_TOOL can be set to "terraform" or "tofu" depending on which tool
# you want to use for deployment.
IAC_TOOL := terraform

# Target to reconfigure the Terraform backend
tf_reconfigure:
	$(IAC_TOOL) -chdir=terraform \
	  init -reconfigure \
	  -backend-config=$(BACKEND_CONFIG_ENDPOINTS) \
	  -backend-config="bucket=$(BACKEND_CONFIG_BUCKET)" \
	  -backend-config="key=$(BACKEND_CONFIG_KEY)" \
	  -backend-config="region=$(BACKEND_CONFIG_REGION)"

# Target to init the Terraform backend
tf_init:
	$(IAC_TOOL) -chdir=terraform \
	  init \
	  -backend-config=$(BACKEND_CONFIG_ENDPOINTS) \
	  -backend-config="bucket=$(BACKEND_CONFIG_BUCKET)" \
	  -backend-config="key=$(BACKEND_CONFIG_KEY)" \
	  -backend-config="region=$(BACKEND_CONFIG_REGION)"

# Target to generate and show the Terraform execution plan
tf_plan: 
	if [ ! -f "terraform/.terraform.lock.hcl" ]; then \
		$(MAKE) -f $(CURRENT_MAKEFILE) tf_init; \
	fi
	$(IAC_TOOL) -chdir=terraform \
	  plan \
		-var-file="variables.tfvars" 

# Target to apply Terraform configuration
tf_apply:
	if [ ! -f "terraform/.terraform.lock.hcl" ]; then \
		$(MAKE) -f $(CURRENT_MAKEFILE) tf_init; \
	fi
	$(IAC_TOOL) -chdir=terraform \
	  apply -auto-approve \
	  -var-file="variables.tfvars"

# Target to destroy all Terraform-managed resources
tf_destroy:
	$(IAC_TOOL) -chdir=terraform \
	  destroy -auto-approve \
		-var-file="variables.tfvars"

create_log_stream_index:
	# getting Token for authentication from Username/Password...
	$(eval OTC_X_AUTH_TOKEN := $(shell ../utils/tokenFromUsername.sh))
	$(eval LOG_GROUP_ID := $(shell $(IAC_TOOL) -chdir=terraform output -raw MyLogGroup_ID))
	$(eval LOG_STREAM_ID := $(shell $(IAC_TOOL) -chdir=terraform output -raw MyLogStream_ID))
	@bash ../utils/createLogStreamIndex.sh $(OTC_X_AUTH_TOKEN) $(LOG_GROUP_ID) $(LOG_STREAM_ID)
	

.PHONY: tf_init tf_plan tf_apply tf_destroy create_log_stream_index

You might want to adjust the following variables to your need:

# Terraform backend configuration
BACKEND_CONFIG_BUCKET := "doc-samples-tf-backend"
BACKEND_CONFIG_KEY := "terraform_state/python/custom-rule-cts-login-check.tf"
BACKEND_CONFIG_REGION := "eu-de"
BACKEND_CONFIG_ENDPOINTS := "endpoints={s3=\"https://obs.eu-de.otc.t-systems.com\"}"

Deploy

To deploy using Terraform run:

make tf_apply

To destroy the deployed resources using Terraform run:

make tf_destroy