This post is a continuum to Part one and Part Two. The focus of this post is adding a basic security condition for the Telegram bot and the challenges during communicating with the bot using PowerShell.

Telegram Bot Security using PowerShell

We learn how to create the Telegram bot and how to send and receive messages in both part 1 and part 2. But surely you don’t want your bot to accept commands from any client. It should only accept commands from trusted clients.

The Telegram Bot is the PowerShell script reading from the Telegram API serivce.

The Telegram Messenger Client is the installed Telegram client on Android/IOS or other platform

To help in securing the Telegram bot, The bot should require a password first before accepting any incoming commands. The password is sent through the Telegram messenger client. In addition to other basic requirements such as the first name, last name.

Let’s start by explaining the used parameters:

  • Token: Its the HTTP API Token, we get this token in Part 1
  • PassPhrase: A text that will be send from the Telegram Messenger client to authenticate. Consider it as the password.
  • FirstName: The Telegram messenger client user first name
  • LastName: The Telegram messenger client last name
  • AllowedCommands: A text file contains all the allowed whitelist PowerShell commands.
[cmdletbinding()]
param(
[parameter(Mandatory=$true)]$Token,  #The HTTP_API Token
[parameter(Mandatory=$true)]$PassPhrase, #A text that will be used to authenticate your client to the bot
[parameter(Mandatory=$true)]$FirstName, # Client First name
[parameter(Mandatory=$true)]$LastName, #Client last name
[parameter(Mandatory=$false)]$AllowedCommands  #a text file which will include the whitelisted PS commands
)
### Variables
$URL='https://api.telegram.org/bot{0}' -f $Token  #the URL 
$AcceptedSession=""   #if this variable is $null, then the user is not authenticated yet.
$LastUnAuthenticatedMessage=""  # will use it as an anchor, as when the script load it will read some previous messages, and the script should take no action or execute the old commands again
$lastexecMessageID="" # the Last command executed, so the command wont be executed twice.

Telegram bot to Authenticate via a passphrase

Your Telegram bot is searchable via the Telegram messenger client. So in Telegram Messenger client search, write Powershell, and you will see multiple bots including your bot, so the last thing you need is to have someone sending a random command to your bot and taking control over your servers.

** This PowerShell script can be enhanced and secured, this is not the best practice, but it’s a good starting point to secure the Telegram bot**

Let’s start by creating a function name it ReadTGMessage and another function named IsAuthenticated which checks first if the message is the PassPhrase or not.

The IsAuthenticated function checks the following condition before considering the session authenticated.

  • Message received should not be matching the last message of the previous chat history session (date-time), to avoid parsing it again and again.
  • Message must be matching the passphrase (password).
  • The sender First name and Last name are trusted.
  • The senderShould not be a Bot.

After the condition above matches, the session will be considered as Authenticated and the $AcceptedSession is set to Authenticated and the function will return the Chat_ID Powershell will use to communicate back.

Please note that the data of the varialbe stored in the memory in a clear text format. So its recommended to encrypte the data.

Function ReadTGMessage{ #Read Incomming message 
    try{
        $inMessage=Invoke-RestMethod -Method Get -Uri ($URL +'/getUpdates') -ErrorAction Stop
        Write-Verbose -Message "Checking for new Messages $($inMessage.result[-1])"
        return $inMessage.result[-1] # Just need the last message, no need for the entire conversation.

    }
    Catch{
        Write-Host $_.exception.message -ForegroundColor red
        return "TGFail"
    }

}

Function IsAuthenticated{ 
param(
    $CheckMessage
)
    Write-Verbose -Message "Checking Authentication Function..."
    if (($messages.message.date -ne $LastUnAuthenticatedMessage) -and ($CheckMessage.message.text -like $PassPhrase) -and ($CheckMessage.message.from.first_name -like $FirstName) -and ($CheckMessage.message.from.last_name -like $LastName) -and ($CheckMessage.message.from.is_bot -like $false)){
    Write-Verbose -Message "Yes yes, Authenticated ...$($messages.message.chat.id)"
    $script:AcceptedSession="Authenticated"
    Write-Host "Auth Accepted..." -ForegroundColor Green
    return $messages.message.chat.id
    }
    Else{
    Write-Host "No Authentication made, or auth failure.." -ForegroundColor Red
    return 0

    }

While ($true){
sleep 1
$messages=ReadTGMessage
        if ($LastUnAuthenticatedMessage -like $null){  # Get the last message in the previous communication and set it as an anchor 
            $LastUnAuthenticatedMessage=$messages.message.date # All the communication should start after that message
           }

if (!($AcceptedSession)){ ## If this value is $null, then the session is not authenticated and all incoming messages should be first sent to the Auth Function
            $CheckAuthentication=IsAuthenticated -CheckMessage $messages
            }
            Else{
            if (($CheckAuthentication -ne 0) -and ($messages.message.text -notlike $PassPhrase) -and ($messages.message.date -ne $lastexecMessageID)){
                      #### The Message is Authenticated, and the command can be executed.
                         try{
                            $Result=Invoke-Expression($messages.message.text) -ErrorAction Stop
                            Write-Host "The Output of the command was the following" -ForegroundColor Green
                            $Result
                            Write-Host "End of Execution--------------" -ForegroundColor Green
                            SendTGMessage -Messagetext $Result -ChatID $messages.message.chat.id
                        }
                        catch {
                            SendTGMessage -Messagetext ($_.exception.message) -ChatID $messages.message.chat.id
                        }
                        Finally{
                            $lastexecMessageID=$messages.message.date
                        }
              }

Limit Accepted Command Scope.

We need to ensure that the Telegram PowerShell bot script won’t execute anything it receives, so whitelist commands are only accepted.

The user should set the path of the text file which contains the whitelisted command as an argument for the AllowedCommands.

The AllowedCommands is a text file contain the allowed command, each command in a separate line such as

Get-Childitem
Get-ACL
New-ADUser

The script in this part checks if the command is listed as a whitelist or not.

Function CommandShouldBeExecuted {
    Param(
    $cmdlet
    )
    Write-Verbose -Message "Checking if the command is safe ..."
    try{
    if ($cmdlet -like "/disconnect"){ #Allow the Admin to un-authenticate him self after finishing the session
    Write-Host "Bye Bye ..." -ForegroundColor Green
    SendTGMessage -Messagetext "See You.. loging off" -ChatID $messages.message.chat.id
    $script:AcceptedSession=$null
        return 0
        
            }

    if (Test-Path $AllowedCommands){
        $commands=Get-Content -Path $AllowedCommands
        if (($commands |where {$_ -like ($cmdlet.split("")[0])}).count -gt 0) {
        Write-Verbose -Message "Command is safe and can be executed"
            return 1 # 1 equal to allowed to execute
            }
            Else{
             Write-Verbose -Message "Not Accepted Command.. "
            return 0 # Nope, don't execute
            }

        }
    }
    catch{
     Write-Verbose -Message "Allowed list not found.. executing anything is accepted."
    return 1 #If the user did not set the path, it means execute all.
    }

}

Part4 demonstrates how the script works and how to use the AllowedCommands in action.

<– Control your Infrastructure using… Telegram Messenger (Part 1 – Create the Bot)
<–Control your Infrastructure using… Telegram Messenger (Part 2 – Send and Receive.)
Control your Infrastructure using… Telegram Messenger (Part 3 – Basic Security)
Control your Infrastructure using… Telegram Messenger (Part 4 – Execution) –>

Rate this post