Friday, December 6, 2024

creating images in ACR

 $CONTAINER_IMAGE_NAME="your_image_name:0.1"

$CONTAINER_REGISTRY_NAME = "your_registry_name"

 

az login --tenant "XXXXXXXXXXXXXXXXXX"

az account set --name azurecloud --subscription "XXXXXXXXXXXXXXXXXXXXXXXX"

 

#This will pick local files

az acr build --registry "$CONTAINER_REGISTRY_NAME" --image "$CONTAINER_IMAGE_NAME" --file "Dockerfile" .


#This will pick remote files

az acr build --registry "$CONTAINER_REGISTRY_NAME" --image "$CONTAINER_IMAGE_NAME" --file "Dockerfile.azure-pipelines" "https://github.com/poorleno1/container-apps-ci-cd-runner-tutorial.git"




various

az acr task create --registry "$CONTAINER_REGISTRY_NAME" --name updateimage --context https://github.com/poorleno1/container-apps-ci-cd-runner-tutorial.git --file Dockerfile.azure-pipelines --image "$CONTAINER_IMAGE_NAME" --commit-trigger-enabled false


--commit-trigger-enabled

Indicates whether the source control commit trigger is enabled.

Thursday, December 5, 2024

Assign permissions to enterprise app using powershell

You might be required to add this storage account to Directory Reader role 



#find-module Microsoft.Graph.Authentication | install-module

Disconnect-Graph
Get-MgContext
Connect-MgGraph -Scopes "Application.Read.All","AppRoleAssignment.ReadWrite.All,RoleManagement.ReadWrite.Directory" -TenantId "XXXXXXXXXXXXXXXXXXXXXXXXX"

Select-MgProfile Beta


$MdId_Name = "ManagementAutomation"

$MdId_ID = (Get-MgServicePrincipal -Filter "displayName eq '$MdId_Name'").id

$graphApp = Get-MgServicePrincipal -Filter "AppId eq '00000003-0000-0000-c000-000000000000'"

$graphScopes = @(
    "User.Read.All"
    "Mail.Send"
    "Mail.ReadWrite"
)


ForEach($scope in $graphScopes){
 
  $appRole = $graphApp.AppRoles | Where-Object {$_.Value -eq $scope}
 
  if ($null -eq $appRole) { Write-Warning "Unable to find App Role for scope $scope"; continue; }
 
 
 
   #Check if permissions isn't already assigned
  $assignedAppRole = Get-MgServicePrincipalAppRoleAssignment -ServicePrincipalId $MdId_ID | Where-Object { $_.AppRoleId -eq $appRole.Id -and $_.ResourceDisplayName -eq "Microsoft Graph" }
 
 
 
  if ($null -eq $assignedAppRole) {
    New-MgServicePrincipalAppRoleAssignment -PrincipalId $MdId_ID -ServicePrincipalId $MdId_ID -ResourceId $graphApp.Id -AppRoleId $appRole.Id
  }else{
    write-host "Scope $scope already assigned"
  }
}



Wednesday, December 4, 2024

Assign administrator roles with PowerShell

 General approach is that you need to get RoleID and then assign enterprise app object ID to this RoleID:


Create an app using CLI:


$app_name = "Deployment app"

$app = az ad app create --display-name $app_name --query '{appId: appId, objectId: id}' --output json

$app = $app | ConvertFrom-Json

$cred = az ad app credential reset --id $app.appId --display-name "client-secret" --years 2

$enapp = az ad sp create --id  $app.appId --query '{appId: appId, objectId: objectId}' --output json 

$enappID = az ad sp show --id  $app.appId --query id --output tsv


Assign it to a role:


$AdminRoleObject = Get-AzureADDirectoryRole| where {$_.DisplayName -eq 'Application Administrator'} 

Add-AzureADDirectoryRoleMember -ObjectId $AdminRoleObject.ObjectId -RefObjectId $enappID


If RoleID do not exist ($AdminRoleObject is empty) enable it:

$template = Get-AzureADDirectoryRoleTemplate | where {$_.DisplayName -eq 'Privileged Role Administrator'} 

Enable-AzureADDirectoryRole -RoleTemplateId $template.ObjectId



Other, assign owner to subscription:

az role assignment create --assignee $app.appId --role "Owner" --scope "/subscriptions/$subscriptionID"

Tuesday, December 3, 2024

list open ports

 lsof -nP -iTCP -sTCP:LISTEN


ss -tunlp

netstat -tnlp


apt-get install procps
apt install net-tools
apt install iproute2 net-tools procps



#!/bin/bash # This script lists processes with open TCP ports by reading /proc/net/tcp and # matching socket inodes to file descriptors in /proc/[pid]/fd directories. # Function to convert hexadecimal port number to decimal. convert_port() { local hex_port=$1 echo $((16#$hex_port)) } echo "Processes with open TCP ports (based on /proc):" printf "%-8s %-20s %-6s\n" "PID" "Process Name" "Port" echo "-------------------------------------------" # Skip the header line from /proc/net/tcp by using tail. tail -n +2 /proc/net/tcp | while read -r line; do # Extract the local address (field 2) and the socket inode (field 10). local_address=$(echo "$line" | awk '{print $2}') inode=$(echo "$line" | awk '{print $10}') # If inode is empty, skip this line. if [[ -z "$inode" ]]; then continue fi # Extract the port (in hex) from the local_address (format: IP:PORT). port_hex=$(echo "$local_address" | cut -d':' -f2) port=$(convert_port "$port_hex") # Use find to look for file descriptors linking to this socket inode. pids=$(find /proc/[0-9]*/fd -lname "socket:\[$inode\]" 2>/dev/null | \ cut -d'/' -f3 | sort -u) # For each matching process, retrieve the process name. for pid in $pids; do if [ -f "/proc/$pid/comm" ]; then pname=$(cat /proc/$pid/comm) else pname="N/A" fi printf "%-8s %-20s %-6s\n" "$pid" "$pname" "$port" done done



List all processes:

#!/bin/bash
# This script lists all processes by scanning the /proc filesystem.

# Print header
printf "%-8s %-s\n" "PID" "Process Name"
printf "%-8s %-s\n" "--------" "----------------"

# Loop over directories in /proc that are numerical
for pid_dir in /proc/[0-9]*; do
    pid=$(basename "$pid_dir")
    
    # Check for the existence of the comm file which contains the process name
    if [ -f "$pid_dir/comm" ]; then
        proc_name=$(cat "$pid_dir/comm")
    else
        proc_name="N/A"
    fi
    
    printf "%-8s %-s\n" "$pid" "$proc_name"
done

Monday, October 28, 2024

Publish CRLs

1. Login to offline RootCA and create a new crl file:

    certutil –crl

2. Copy CRL file from C:\Windows\System32\Certsrv\CertEnroll\ to a USB

3. on Issuing servers upload crl file to C:\inetpub\wwwroot\pki and other locations that CRL should be uploaded to like share or AD.

Publish in AD with: certutil –dspublish -f C:\CRKRoot.crl




Some Kusto queries

 1. Find resource using TLS lower than 1.2:

resources
where type in (
    'microsoft.web/sites/config',
    'microsoft.storage/storageaccounts',
    'microsoft.sql/servers',
    'microsoft.network/applicationgateways',
    'microsoft.cdn/profiles/endpoints',
    'microsoft.apimanagement/service',
    'microsoft.network/virtualnetworkgateways',
    'microsoft.signalrservice/signalr',
    'microsoft.servicebus/namespaces',
    'microsoft.containerservice/managedclusters'
)
extend TlsVersion = case(
    type == 'microsoft.web/sites/config', properties.minTlsVersion,
    type == 'microsoft.storage/storageaccounts', properties.minimumTlsVersion,
    type == 'microsoft.sql/servers', properties.minimalTlsVersion,
    type == 'microsoft.network/applicationgateways', properties.sslPolicy.minProtocolVersion,
    type == 'microsoft.cdn/profiles/endpoints', properties.tlsSettings.protocolType,
    type == 'microsoft.apimanagement/service', tostring(properties.protocols),
    type == 'microsoft.network/virtualnetworkgateways', tostring(properties.vpnClientConfiguration.vpnClientProtocols),
    type == 'microsoft.signalrservice/signalr', properties.tls.minimalTlsVersion,
    type == 'microsoft.servicebus/namespaces', properties.minimumTlsVersion,
    type == 'microsoft.containerservice/managedclusters''TLS managed by individual deployments',
    'Unknown')
where TlsVersion !contains "1.2" and TlsVersion != "Unknown" and TlsVersion != "TLS1_2"
project ResourceType = type, 
          ResourceName = name, 
          Location = location, 
          TlsVersion


2.Find blocked queried in app gateway

AzureDiagnostics
| where ResourceProvider == "MICROSOFT.NETWORK"
| where Category == "ApplicationGatewayFirewallLog"
| where action_s == "Matched"
| project
    TimeGenerated,
    ClientIP = clientIp_s,
    RequestURI = requestUri_s,
    RuleId = ruleId_s,
    RuleSetType = ruleSetType_s,
    Action = action_s,
    Message,
    Hostname = hostname_s,
    TransactionId = transactionId_g
| sort by TimeGenerated desc
 

3. Find timeouts:


AzureDiagnostics

| where Category == "ApplicationGatewayAccessLog"

| where httpStatus_d in (408, 504, 502)  // Common timeout-related HTTP status codes

| where host_s == "ylukscaleprod.eu.yusen-logistics.com"


4. Statistics, success rate in every 5 minute slot:


AzureDiagnostics

| where ResourceType == "APPLICATIONGATEWAYS"

| where Category == "ApplicationGatewayFirewallLog" or Category == "ApplicationGatewayAccessLog"

| where TimeGenerated >= ago(30d) // Adjust timeframe as needed

| where listenerName_s == "https-ylukscaleprod-eu-yusen-logisitcs-com" // Filter for specific listener if needed

| extend ListenerName = listenerName_s

| extend ResponseCode = httpStatus_d

| extend IsHealthy = iff(ResponseCode >= 200 and ResponseCode < 400, true, false)

| summarize 

    TotalRequests = count(),

    FailedRequests = countif(not(IsHealthy)),

    SuccessRate = (count() - countif(not(IsHealthy))) * 100.0 / count()

    by bin(TimeGenerated, 5m), ListenerName, _ResourceId

| extend IsDown = iff(SuccessRate < 50, true, false) // Define downtime threshold

| order by TimeGenerated desc



5. Success rate in last 7 dates:


AzureDiagnostics

| where ResourceType == "APPLICATIONGATEWAYS"

| where Category == "ApplicationGatewayFirewallLog" or Category == "ApplicationGatewayAccessLog"

| where TimeGenerated >= ago(30d) // Adjust timeframe as needed

| where listenerName_s == "https-ylukscaleprod-eu-yusen-logisitcs-com" // Filter for specific listener if needed

| extend ListenerName = listenerName_s

| extend ResponseCode = httpStatus_d

| extend IsHealthy = iff(ResponseCode >= 200 and ResponseCode < 400, true, false)

| summarize 

    TotalRequests = count(),

    FailedRequests = countif(not(IsHealthy)),

    SuccessRate = (count() - countif(not(IsHealthy))) * 100.0 / count()

    by bin(TimeGenerated, 5m), ListenerName, _ResourceId

| extend IsDown = iff(SuccessRate < 50, true, false) // Define downtime threshold

| order by TimeGenerated desc



6. Statistics with error code failures and successes:

AzureDiagnostics

| where ResourceProvider == "MICROSOFT.NETWORK"

| where Category == "ApplicationGatewayFirewallLog"

| where action_s == "Matched"

| where hostname_s == "ylukscaleprod.eu.yusen-logistics.com"

| project

    TimeGenerated,

    ClientIP = clientIp_s,

    RequestURI = requestUri_s,

    RuleId = ruleId_s,

    RuleSetType = ruleSetType_s,

    Action = action_s,

    Message,

    Hostname = hostname_s,

    TransactionId = transactionId_g

| sort by TimeGenerated desc


Tuesday, October 15, 2024

Converting VM to generation 2 in Hyper-v

 1. Create a VM from vagrant, this is gen1.

2. Although disk is VHDX, export it, add more space in Hyper-V

3. Attach this drive to old VM and expand drive is disk management.

4. Convert to GPT using MBR2GPT.

    mbr2gpt.exe /validate /disk:1 /allowFullOS

    mbr2gpt.exe /convert /disk:1 /allowFullOS 

This will create a partition at the end.



5. Create a new VM (Gen2) and use exported drive.