• Facebook
  • Twitter
  • Youtube
  • LinedIn
  • RSS
  • Docs
  • Comparisons
  • Blogs
  • Download
  • Contact Us
Download
Show / Hide Table of Contents

Security Configuration

NCache security on Azure has two main parts:

  • TLS encryption: It encrypts communication between NCache clients and servers.

  • Node-level security: Node level security helps you control which users can administer NCache servers and caches.

This section guides you through enabling TLS (Transport Layer Security) and node-level security for the NCache servers deployed on Azure.

Important

For best results, configure security before scaling up the VMSS. If security is enabled after servers are already running, it will only be applied to newly created instances. Existing instances will not be updated automatically. Therefore, it is recommended to:

  • Scale down the Azure VMSS to 0 instances.
  • Apply the security (TLS or NCache security) configurations.
  • Then scale up the deployment.

Enable TLS

TLS ensures secure communication between NCache servers and clients. To enable TLS, NCache provides a custom script via GitHub that you can modify and execute within your environment. Follow the steps below to apply the script:

  • Navigate to Resource Group: In the Azure portal, navigate to and open the Resource Group where your NCache application is deployed.

    Resource Group

  • Configure Settings: Open the Virtual Machine Scale Set (VMSS) associated with your cluster. In the left-hand menu, locate and expand the Settings section.

    Resource Group

  • Script for TLS Certificate Installation: Select Operating System from the settings menu. On the resulting screen, check the Modify Custom Data box and paste the following security script, into the Custom Data block and click Apply.

    Note

    The CustomData script does not transmit certificate details or sensitive information to NCache or any external systems. These commands are executed locally by the Azure VM agent on each node within the Scale Set during the provisioning or extension update process.

    # This script installs the client and root CA certificates for NCache and enables TLS for NCache communication.
    # Note: You need to have the NCache PowerShell module installed to run this script.
    # You also need to have the certificate files (root CA certificate and client certificate in pfx format) saved in a location accessible to the script, and provide the correct paths, password, CN and thumbprint in the variables below before running the script.
    
    # VARIABLES (PLEASE UPDATE THESE VARIABLES BEFORE RUNNING THE SCRIPT)
    # copy your root repo where you have saved the cert files (rootCA.crt and cert.pfx)
    $rootRepoUri = "YOUR_ROOT_REPO_URI"
    # copy your cert names, password, CN and thumbprint here
    $certUri = "$rootRepoUri/rootCA.crt"
    $certFilePath = "C:\rootCA.crt"
    $pfxUri = "$rootRepoUri/cert.pfx"
    $pfxFilePath = "C:\cert.pfx"
    $certPasscode = "YOUR_CERT_PASSWORD"
    $certCN = "YOUR_CERT_CN"
    $serverThumbprint = "YOUR_CERT_THUMBPRINT"
    
    function Install-NCacheCertificate {
        param (
            [Parameter(Mandatory = $true)][string]$PfxFilePath,
            [Parameter(Mandatory = $true)][string]$CertFilePath,
            [Parameter(Mandatory = $true)][string]$CertPasscode
        )
        try {
            # Install root CA certificate
            if (Test-Path $CertFilePath) {
                Write-Host "Installing root CA certificate from $CertFilePath"
                Import-Certificate -FilePath $CertFilePath -CertStoreLocation Cert:\LocalMachine\Root | Out-Null
                Write-Host "Root CA certificate installed successfully"
            }
            else {
                Write-Host "Root CA certificate file not found at $CertFilePath"
            }
    
            # Install client certificate
            if (Test-Path $PfxFilePath) {
                Write-Host "Installing client certificate from $PfxFilePath"
                $pfxPassword = ConvertTo-SecureString -String $CertPasscode -AsPlainText -Force
                Import-PfxCertificate -FilePath $PfxFilePath -CertStoreLocation Cert:\LocalMachine\My -Password $pfxPassword | Out-Null
                Write-Host "Client certificate installed successfully"
            }
            else {
                Write-Host "Client certificate file not found at $PfxFilePath"
            }
        }
        catch {
            Write-Host "Error occurred while installing NCache certificate: $($_.Exception.Message)"
        }
        finally {
            if (Test-Path $CertFilePath) {
                Remove-Item $CertFilePath -Force -ErrorAction SilentlyContinue
            }
            if (Test-Path $PfxFilePath) {
                Remove-Item $PfxFilePath -Force -ErrorAction SilentlyContinue
            }
        }
    }
    
    function Enable-NCacheCertificate {
        param (
            [Parameter(Mandatory = $true)][string]$NodeIp,
            [Parameter(Mandatory = $true)][string]$CertificateCN,
            [Parameter(Mandatory = $true)][string]$ServerThumbprint
        )
    
        try {        
            Enable-NCacheTLS -Node $NodeIp -ServerCertificateCN $CertificateCN -ServerCertificateThumbprint $ServerThumbprint -ServerToServerCommunication -ClientServerCommunication
    
            Write-Host "TLS enabled for NCache"
        }
        catch {
            Write-Host "Error occured while enabling TLS for NCache: $($_.Exception.Message)"
        }
    }
    
    # saving cert file
    Invoke-WebRequest -Uri $certUri -OutFile $certFilePath -UseBasicParsing
    
    # saving pfx file
    Invoke-WebRequest -Uri $pfxUri -OutFile $pfxFilePath -UseBasicParsing
    
    # install cert on windows
    Install-NCacheCertificate -PfxFilePath $pfxFilePath -CertFilePath $certFilePath -CertPasscode $certPasscode
    
    # the following script needs to be executed on the node separately after installing NCache
    $serviceName = "ncachesvc"
    $service = Get-Service -Name $serviceName -ErrorAction SilentlyContinue
    if ($service) {
        Import-Module "C:\Program Files\NCache\bin\tools\ncacheps\ncacheps.psd1"
    
        # enable TLS for NCache
        $localNodeIp = Get-NetRoute -DestinationPrefix "0.0.0.0/0" | Sort-Object RouteMetric | Select-Object -First 1 | Get-NetIPAddress | Where-Object { $_.AddressFamily -eq 'IPv4' } | Select-Object -ExpandProperty IPAddress
        $CertificateCN = $certCN
        $ServerThumbprint = $serverThumbprint
        Enable-NCacheTLS -Node $localNodeIp -ServerCertificateCN $CertificateCN -ServerCertificateThumbprint $ServerThumbprint -ServerToServerCommunication
    
        # restart NCache service to apply TLS settings
        Stop-Service -Name $serviceName -Force -ErrorAction Stop
        Start-Sleep -Seconds 5
        Start-Service -Name $serviceName -ErrorAction Stop
    }
    
    • Certificate Installation: It downloads a root CA and a client PFX certificate from a user-provided repository and installs them into the local machine's certificate store.

    • Enabling TLS: It utilizes the Enable-NCacheTLS command to bind the certificates to the NCache service for both client-to-server and server-to-server communication.

    • Service Restart: It automatically restarts the NCache service (ncachesvc) to apply the new security settings.

  • The above script would be pasted in the Custom Data box shown in the image below. This script ensures that all data transferred between NCache clients and servers is encrypted using Transport Layer Security (TLS).

    Modify Custom Data

Enable NCache Security

Node-level security controls administrative access to NCache servers by defining authorized users (Node Administrators) who can perform cache management operations such as creating, modifying, and removing caches. The process to enable node-level security is the same as enabling TLS, with the only difference being the script used.

  • Follow the same steps as described in Enable TLS to open and modify the Custom Data box and paste the following enable-security.ps1 and click Apply.

    # This script automates the process of joining a Windows machine to a domain and then configuring NCache security by adding a specified domain user or group with admin permissions to NCache. The script is designed to be run on a machine that is not yet part of the domain, and it will handle the domain join process as well as the post-reboot configuration needed for NCache security setup. The script includes error handling and logging to provide feedback on the operations being performed.
    # Note: You need to have the NCache PowerShell module installed to run this script.
    # You also need to have the necessary permissions to join the machine to the domain and to add users/groups to NCache with admin permissions. Additionally, ensure that the machine can communicate with the domain controller and that the provided credentials are correct.
    
    # Define the necessary variables for domain join and NCache security configuration. You need to replace the placeholder values with actual values before running the script.
    $domainName = "YOUR_DOMAIN_NAME" # e.g. corp.diyatech-dev.com
    $domainAdminPassword = "YOUR_DOMAIN_ADMIN_PASSWORD"
    $domainUser = "YOUR_DOMAIN_USER"
    $interfaceAlias = "Ethernet"
    $dnsServer = "YOUR_DNS_SERVER_IP"
    $UserOrGroupDN = "YOUR_USER_OR_GROUP_DN" # e.g. CN=CacheAdmins,OU=Groups,DC=corp,DC=diyatech-dev,DC=com
    
    # Get the local node IP address to use for NCache configuration later
    $localNodeIp = (Get-NetRoute -DestinationPrefix "0.0.0.0/0" | Sort-Object RouteMetric | Select-Object -First 1 | Get-NetIPAddress | Where-Object { $_.AddressFamily -eq 'IPv4' } | Select-Object -ExpandProperty IPAddress)
    
    function Install-NCacheSecurity {
        param (
            [Parameter(Mandatory = $true)][string]$DomainName,
            [Parameter(Mandatory = $true)][string]$AdminPassword,
            [Parameter(Mandatory = $true)][string]$DomainUser,
            [Parameter(Mandatory = $true)][string]$InterfaceAlias,
            [Parameter(Mandatory = $true)][string]$DnsServer
        )
        try {
            # Configure DNS
            Write-Host "Configuring DNS server to $DnsServer on interface $InterfaceAlias"
            Set-DnsClientServerAddress -InterfaceAlias $InterfaceAlias -ServerAddresses $DnsServer
            Write-Host "DNS configured successfully"
    
            # Join domain using domain administrator credentials
            Write-Host "Joining domain $DomainName"
    
            # Convert the plain text password to a secure string and create a credential object for the domain admin
            $password = ConvertTo-SecureString $AdminPassword -AsPlainText -Force
            $Cred = New-Object System.Management.Automation.PSCredential ($DomainUser, $password)
            Add-Computer -DomainName $DomainName -Credential $Cred -Restart:$false -Force
            Write-Host "Domain joined successfully (no restart yet)"
            Start-Sleep -Seconds 5
    
            # Add DomainUser to local Administrators BEFORE restart
            Add-DomainUserToLocalAdmins -DomainName $DomainName -DomainUser $DomainUser
            Start-Sleep -Seconds 5
    
            # Now restart to complete domain join
            Write-Host "Restarting machine to finalize domain join..."
            Restart-Computer -Force
            Write-Host "Machine restart initiated"
        }
        catch {
            Write-Host "Error occurred while configuring domain join: $($_.Exception.Message)"
        }
    }
    
    function Add-DomainUserToLocalAdmins {
        param (
            [Parameter(Mandatory = $true)][string]$DomainName,
            [Parameter(Mandatory = $true)][string]$DomainUser
        )
        try {
            $fullDomainUser = "$DomainName\$DomainUser"
    
            # Check if the domain can be resolved before attempting to add the user to local admins
            if (Resolve-DnsName -Name $DomainName -ErrorAction SilentlyContinue) {
                Write-Host "Domain $DomainName resolved successfully"
            }
    
            # Add the specified domain user to the local Administrators group
            Write-Host "Adding $fullDomainUser to local Administrators group"
            $currentMembers = Get-LocalGroupMember -Group "Administrators" | Where-Object { $_.Name -eq $fullDomainUser }
    
            # Only add the user if they are not already a member of the local Administrators group
            if (-not $currentMembers) {
                Add-LocalGroupMember -Group "Administrators" -Member $fullDomainUser -ErrorAction Stop
                Write-Host "$fullDomainUser added to local Administrators successfully"
            }
            else {
                Write-Host "$fullDomainUser already exists in local Administrators group"
            }
        }
        catch {
            Write-Host "Error adding $DomainUser to Administrators: $($_.Exception.Message)"
        }
    }
    
    function Set-TaskScheduler {
        param (
            [Parameter(Mandatory = $true)][string]$TaskName,
            [Parameter(Mandatory = $true)][string]$FilePath,
            [Parameter(Mandatory = $false)][switch]$AtStartup
        )
    
        try {
            $action = New-ScheduledTaskAction `
                -Execute "powershell.exe" `
                -Argument "-NoProfile -ExecutionPolicy Bypass -File `"$FilePath`""
    
            if ($AtStartup) {
                $trigger = New-ScheduledTaskTrigger -AtStartup
            }
    
            $settings = New-ScheduledTaskSettingsSet `
                -StartWhenAvailable `
                -AllowStartIfOnBatteries `
                -DontStopIfGoingOnBatteries `
                -RestartCount 3 `
                -RestartInterval (New-TimeSpan -Minutes 1)
    
            Register-ScheduledTask `
                -TaskName $TaskName `
                -Action $action `
                -Trigger $trigger `
                -Settings $settings `
                -RunLevel Highest `
                -User "SYSTEM" `
                -Force
    
            Write-Host "$TaskName task scheduled at startup successfully (no parameters needed)"
        }
        catch {
            Write-Host "Failed to set $TaskName task: $($_.Exception.Message)"
        }  
    }
    
    # CREATE POST-REBOOT SCRIPT FILE (TO BE EXECUTED AFTER REBOOT TO COMPLETE NCache SECURITY SETUP)
    $postRebootScriptPath = "C:\Enable-NCacheSecurityPostReboot.ps1"
    $scriptContent = @"
    # POST-REBOOT NCache SECURITY SETUP
    `$NodeIp = '$localNodeIp'
    `$NCacheUserOrGroupName = '$domainUser'
    `$UserOrGroupDN = '$UserOrGroupDN'
    `$DomainController = '$dnsServer'
    `$AdminUsername = '$domainUser'
    `$AdminPassword = '$domainAdminPassword'
    
    try {
        # Prepare admin credentials for NCache operations
        `$password = ConvertTo-SecureString `$AdminPassword -AsPlainText -Force
        `$adminCred = New-Object System.Management.Automation.PSCredential (`$AdminUsername, `$password)
        Write-Host "NCache admin credentials prepared for `$AdminUsername"
    
        # Import NCache PowerShell module
        `$ncacheModulePath = "C:\Program Files\NCache\bin\tools\ncacheps\ncacheps.psd1"
        if (Test-Path `$ncacheModulePath) {
            Import-Module `$ncacheModulePath -Force
            Write-Host "NCache PowerShell module loaded"
        }
        else {
            throw "NCache PowerShell module not found at `$ncacheModulePath"
        }
    
        # Add NCache User/Group with Admin permissions
        Write-Host "Adding NCache group '`$NCacheUserOrGroupName' with Admin access to server `$NodeIp"      
        Add-NCacheUserOrGroup -Server `$NodeIp -AccessLevel Admin -AdminCredentials `$adminCred -UserOrGroupName `$NCacheUserOrGroupName -UserOrGroupDN `$UserOrGroupDN -DomainController `$DomainController -EnableSecurity Yes    
        Write-Host "SUCCESS: NCache group '`$NCacheUserOrGroupName' added with Admin access"
    
        # Cleanup - Delete this script after successful execution
        Remove-Item `$PSCommandPath -Force -ErrorAction SilentlyContinue
        Write-Host "Post-reboot script self-deleted after success"
    }
    catch {
        Write-Host "ERROR in NCache security setup: `$(\$_.Exception.Message)"
        Write-Host "Full error details: `$($_.Exception | Format-List -Force | Out-String)"
    }
    "@
    
    # Write post-reboot script to file
    Out-File -FilePath $postRebootScriptPath -InputObject $scriptContent -Encoding UTF8 -Force
    Write-Host "Post-reboot script created at $postRebootScriptPath with hardcoded values"
    
    # 1. SCHEDULE POST-REBOOT TASK
    Set-TaskScheduler -TaskName "NCacheSecurityPostReboot" -FilePath $postRebootScriptPath -AtStartup
    
    # 2. EXECUTE DOMAIN JOIN (THIS WILL RESTART)
    Install-NCacheSecurity -DomainName $domainName `
        -AdminPassword $domainAdminPassword `
        -DomainUser $domainUser `
        -InterfaceAlias $interfaceAlias `
        -DnsServer $dnsServer
    

This script automates the orchestration required to establish Node-Level Security by integrating NCache servers into an Active Directory domain and authorizing administrative users. Since domain membership requires a system restart for security identifiers (SIDs) to propagate, the automation logic is executed in two distinct phases:

  • Phase 1: Initial Environment Provisioning (Pre-Reboot) The primary objective of this phase is to establish network trust and persist the security logic across a system restart.

    • Active Directory Integration: Using the provided administrative credentials, the script joins the server to the specified domain.

    • Privilege Escalation: The specified domain user is added to the local Administrators group. This step is mandatory to ensure the user possesses the necessary security permissions to modify NCache service configurations post-restart.

    • Task Scheduling for Persistence: As NCache security commands require a domain-authenticated context, the script generates a secondary payload (C:\Enable-NCacheSecurityPostReboot.ps1) and registers it as a Windows Scheduled Task set to trigger at AtStartup.

  • Phase 2: Security Policy Enforcement (Post-Reboot) Upon system restart, the scheduled task initializes the finalized security configuration:

    • NCache PowerShell Module Initialization: The script imports the ncacheps module from the NCache installation directory (%NCHOME%\bin\tools\ncacheps) to expose the management cmdlets.

    • Security Authorization: The script executes the Add-NCacheUserOrGroup cmdlet. This is the core administrative action that enables NCache security and grants Admin level access to the specified domain users or groups.

    • Payload Sanitization: Following the successful application of security policies, the script performs self-cleanup by deleting the temporary post-reboot file to adhere to system security best practices.

Execute Extension Script

After pasting the required script (TLS or Security) into the Custom Data field, you must run the following automation script on your local machine. This script triggers the Azure Custom Script Extension, which extracts the data from the VMSS and executes it on every node.

  • Execute Connect-AzAccount: Please execute the Connect-AzAccount cmdlet in your PowerShell instance, before executing the following script.

  • Execute the Script: After applying, you can execute the script by running the following add-CustomScriptextension.ps1 script on your local machine.

    # This script adds a Custom Script Extension to an existing VMSS. The extension will copy the CustomData.bin file to CustomScript.ps1 and execute it on each VM in the scale set.
    # Note: You need to have the Azure PowerShell module installed and be logged in to your Azure account to run this script.
    
    # Define the Managed Resource Group name and Environment name
    $mrgName = Read-Host "Enter Managed Resource Group name"
    $envName = Read-Host "Enter Environment name"
    
    if (-not $mrgName) {
    Write-Host "Please enter the Managed Resource Group name in the script." -ForegroundColor Red
    return
    }
    if (-not $envName) {
    Write-Host "Please enter the Environment name in the script." -ForegroundColor Red
    return
    }
    
    # Get the VMSS object
    $vmss = Get-AzVmss `
    -ResourceGroupName $mrgName `
    -VMScaleSetName $envName
    
    if (-not $vmss) {
    Write-Host "VMSS not found. Please check the Managed Resource Group name and Environment name." -ForegroundColor Red
    return
    }
    
    # Add the Custom Script Extension to the VMSS
    Add-AzVmssExtension `
    -VirtualMachineScaleSet $vmss `
    -Name "CustomScript" `
    -Publisher "Microsoft.Compute" `
    -Type "CustomScriptExtension" `
    -TypeHandlerVersion "1.10" `
    
    # Update the VMSS with the new extension
    Update-AzVmss `
    -ResourceGroupName $mrgName `
    -Name $envName `
    -VirtualMachineScaleSet $vmss
    

    This script automates the prerequisite environment configuration required for a successful NCache Cloud deployment as follows:

    • Targeting the Cluster: The script prompts for the Managed Resource Group and Environment name to uniquely identify which NCache cluster should receive the configuration.

    • Extension Injection: It adds the CustomScriptExtension to the VMSS object. This specific Azure extension allows you to programmatically run PowerShell scripts inside virtual machines without needing to manually log into each one.

    • Execution Logic: Once added, it instructs the VMSS to take the data you previously saved in the "Custom Data" field which Azure stores internally as CustomData.bin and convert it back into a executable PowerShell script (CustomScript.ps1) on every VM node.

    • Global Update: The Update-AzVmss command triggers a rolling update across the scale set, ensuring that the security settings (like TLS or node-level security) are applied to every server in the cluster simultaneously.

After execution, the chosen security features will be active on your NCache instance.

See Also

Azure Virtual Machine Scale Sets
NCache Deployment

Contact Us

PHONE

+1 214-619-2601   (US)

+44 20 7993 8327   (UK)

 
EMAIL

sales@alachisoft.com

support@alachisoft.com

NCache
  • Edition Comparison
  • NCache Architecture
  • Benchmarks
Download
Pricing
Try Playground

Deployments
  • Cloud (SaaS & Software)
  • On-Premises
  • Kubernetes
  • Docker
Technical Use Cases
  • ASP.NET Sessions
  • ASP.NET Core Sessions
  • Pub/Sub Messaging
  • Real-Time ASP.NET SignalR
  • Internet of Things (IoT)
  • NoSQL Database
  • Stream Processing
  • Microservices
Resources
  • Magazine Articles
  • Third-Party Articles
  • Articles
  • Videos
  • Whitepapers
  • Shows
  • Talks
  • Blogs
  • Docs
Customer Case Studies
  • Testimonials
  • Customers
Support
  • Schedule a Demo
  • Forum (Google Groups)
  • Tips
Company
  • Leadership
  • Partners
  • News
  • Events
  • Careers
Contact Us

  • EnglishChinese (Simplified)FrenchGermanItalianJapaneseKoreanPortugueseSpanish

  • Contact Us
  •  
  • Sitemap
  •  
  • Terms of Use
  •  
  • Privacy Policy
© Copyright Alachisoft 2002 - . All rights reserved. NCache is a registered trademark of Diyatech Corp.
Back to top