diff --git a/Images/SecuirtyCopilotAPIs/EnterpriseApp.png b/Images/SecuirtyCopilotAPIs/EnterpriseApp.png new file mode 100644 index 00000000..67460460 Binary files /dev/null and b/Images/SecuirtyCopilotAPIs/EnterpriseApp.png differ diff --git a/Images/SecuirtyCopilotAPIs/EnterpriseAppGroup.png b/Images/SecuirtyCopilotAPIs/EnterpriseAppGroup.png new file mode 100644 index 00000000..011f7b7c Binary files /dev/null and b/Images/SecuirtyCopilotAPIs/EnterpriseAppGroup.png differ diff --git a/Images/SecuirtyCopilotAPIs/EnterpriseAppSecret.png b/Images/SecuirtyCopilotAPIs/EnterpriseAppSecret.png new file mode 100644 index 00000000..a4b84996 Binary files /dev/null and b/Images/SecuirtyCopilotAPIs/EnterpriseAppSecret.png differ diff --git a/Images/SecuirtyCopilotAPIs/ExportAdminBackOff.png b/Images/SecuirtyCopilotAPIs/ExportAdminBackOff.png new file mode 100644 index 00000000..db4d9929 Binary files /dev/null and b/Images/SecuirtyCopilotAPIs/ExportAdminBackOff.png differ diff --git a/Images/SecuirtyCopilotAPIs/ExportAdminSchema.png b/Images/SecuirtyCopilotAPIs/ExportAdminSchema.png new file mode 100644 index 00000000..c55512de Binary files /dev/null and b/Images/SecuirtyCopilotAPIs/ExportAdminSchema.png differ diff --git a/Images/SecuirtyCopilotAPIs/GraphAPIResponse.png b/Images/SecuirtyCopilotAPIs/GraphAPIResponse.png new file mode 100644 index 00000000..7b185c11 Binary files /dev/null and b/Images/SecuirtyCopilotAPIs/GraphAPIResponse.png differ diff --git a/Images/SecuirtyCopilotAPIs/GraphApiPermissions.png b/Images/SecuirtyCopilotAPIs/GraphApiPermissions.png new file mode 100644 index 00000000..575ad32d Binary files /dev/null and b/Images/SecuirtyCopilotAPIs/GraphApiPermissions.png differ diff --git a/Images/SecuirtyCopilotAPIs/GraphApiRedirect.png b/Images/SecuirtyCopilotAPIs/GraphApiRedirect.png new file mode 100644 index 00000000..f2a5e89d Binary files /dev/null and b/Images/SecuirtyCopilotAPIs/GraphApiRedirect.png differ diff --git a/Security Copilot APIs/ExportAdminAPI/README.md b/Security Copilot APIs/ExportAdminAPI/README.md new file mode 100644 index 00000000..b0c01c2b --- /dev/null +++ b/Security Copilot APIs/ExportAdminAPI/README.md @@ -0,0 +1,240 @@ +# Security Copilot Export Admin APIs + +A PowerShell script to export prompts and evaluations data from Microsoft Security Copilot using the Admin Export APIs. + + +## Overview + +This script demonstrates how to authenticate with Microsoft Security Copilot's Admin APIs and export telemetry data including prompts and evaluations from your workspace. It's useful for auditing, compliance, analytics, and understanding usage patterns within your Security Copilot environment. + +
+ +
+ + +## Features + +- **Authentication**: Uses Entra ID Enterprise Application credentials (Client ID/Secret) to obtain Bearer tokens +- **Date Range Filtering**: Configurable time range for data export (default: last 365 days) +- **Pagination Support**: Handles continuation tokens to retrieve all available data +- **Rate Limiting**: Implements exponential back-off retry logic for HTTP 429 responses +- **Formatted Console Output**: Color-coded display of exported data in real-time +- **CSV Export**: Automatically exports data to CSV files for further analysis +- **Two Resource Types**: + - **Prompts**: User queries, skills executed, and agent interactions + - **Evaluations**: Assessment results and metrics + +## Prerequisites + +- PowerShell 5.1 or higher +- Microsoft Security Copilot instance +- Entra ID Enterprise Application with: + - Client ID + - Client Secret + - Tenant ID + - Security Copilot Owner role + +## Setup + +### 1. Create an Enterprise Application in Entra ID + +1. Navigate to **Azure Active Directory** > **App registrations** > **New registration** +2. Name your application (e.g., "Security Copilot Export") +3. Register the application +4. Note the **Application (client) ID** and **Directory (tenant) ID** + +
+ +
+ + +### 2. Generate Client Secret + +1. Go to **Certificates & secrets** > **New client secret** +2. Add a description and set expiration +3. Copy the secret value (you won't be able to see it again) + +
+ +
+ +### 3. Configure API Permissions + +1. Provide the **Security Copilot Owner role** to the application as described [here](https://learn.microsoft.com/en-us/copilot/security/activity-export-api#authenticating-with-a-service-principal) + +
+ +
+ +### 4. Update Script Variables + +Edit the script and replace the following variables with your values: + +```powershell +$tenantId = "YOUR-TENANT-ID" +$clientId = "YOUR-CLIENT-ID" +$clientSecret = "YOUR-CLIENT-SECRET" +``` + +⚠️ **Security Warning**
+Never commit credentials to version control. Consider using Azure Key Vault or environment variables for production use. + +## Usage + +Run the script in PowerShell: + +```powershell +.\SecurityCopilotExportAdminAPIs.ps1 +``` + +The script will: +1. Authenticate with Entra ID +2. Fetch all prompts from the specified date range +3. Fetch all evaluations from the specified date range +4. Display formatted output in the console +5. Export data to CSV files: + - `prompts_export.csv` + - `evaluations_export.csv` + +## Configuration + +### Date Range + +Modify the date range by adjusting these variables: + +```powershell +$endDate = (Get-Date).ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffZ") +$startDate = (Get-Date).AddDays(-365).ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffZ") +``` + +### Retry Settings + +Adjust rate limiting behavior: + +```powershell +Get-SecurityCopilotData -ResourceType "prompts" ` + -BearerToken $bearerToken ` + -StartDate $startDate ` + -EndDate $endDate ` + -MaxRetries 5 ` + -InitialWaitTime 60 +``` + +- `MaxRetries`: Maximum number of retry attempts for rate limiting (default: 5) +- `InitialWaitTime`: Initial wait time in seconds before retrying (default: 60) + +## Output Data Structure + +### Prompts Export + +The prompts CSV includes fields such as: +- `sessionId`: Unique session identifier +- `promptId`: Unique prompt identifier +- `source`: Origin of the prompt (e.g., immersive, LogicApp) +- `promptType`: Type (Prompt or Skill) +- `content`: The actual prompt text (for promptType="prompt") +- `skillName`: Name of the skill executed (for promptType="skill") +- `inputs`: Skill input parameters +- `createdAt`: Timestamp of creation +- `workspaceId`: Workspace identifier + +### Evaluations Export + +Contains evaluation metrics and assessment results for executed prompts. + +## API Endpoints + +The script uses the following Security Copilot Admin APIs: + +``` +GET https://api.securitycopilot.microsoft.com/exports/prompts?startDate={date}&endDate={date} +GET https://api.securitycopilot.microsoft.com/exports/evaluations?startDate={date}&endDate={date} +``` + +## Error Handling + +The script includes robust error handling for: +- **HTTP 429 (Rate Limiting)**: Exponential back-off retry logic +- **Authentication failures**: Clear error messages +- **Empty responses**: Graceful termination +- **Network errors**: Exception catching and reporting + +
+ +
+ +## Example Output + +``` +------------------------------------------------------------- +[PROMPTS] Fetching data from 2023-12-08T00:00:00.000Z to 2024-12-08T00:00:00.000Z +------------------------------------------------------------- +[API CALL] https://api.securitycopilot.microsoft.com/exports/prompts?startDate=... + + ----------------------------------------------------------- + | Session ID : d3b69430-80bf-40fc-a9bf-109318330977 + | Prompt ID : ac156bf3-9a45-44c3-8bab-60402c2dea4c + | Source : immersive + | Prompt Type : Skill + | Skill Name : ExecuteADXQuery + | Inputs : @{kqlquery=SigninLogs} + ----------------------------------------------------------- + +[INFO] Fetched 50 prompts in this batch +[PROGRESS] Total prompts fetched so far: 50 + +------------------------------------------------------------- +[SUCCESS] Exported 828 prompts to prompts_export.csv +------------------------------------------------------------- +``` + +## Security Best Practices + +1. **Credential Management**: + - Use Azure Key Vault for production environments + - Rotate client secrets regularly + - Never commit secrets to source control + +2. **Principle of Least Privilege**: + - Grant only necessary API permissions + - Use dedicated service accounts + +3. **Data Protection**: + - Encrypt exported CSV files at rest + - Control access to export data + - Implement data retention policies + +## Troubleshooting + +### Authentication Errors +- Verify client ID, secret, and tenant ID are correct +- Check if the client secret has expired + +### Rate Limiting +- Increase `InitialWaitTime` or `MaxRetries` +- Reduce the date range to fetch less data per execution +- Consider scheduling exports during off-peak hours + +### Empty Results +- Verify the date range includes activity +- Check if you have access to the workspace +- Ensure prompts/evaluations exist in the specified timeframe + +## License + +This project is provided as-is for educational and demonstration purposes. + +## Contributing + +Contributions, issues, and feature requests are welcome! + +## Author + +[Mario Cuomo](https://www.linkedin.com/in/mariocuomo/) + +## References + +- [Microsoft Security Copilot Documentation](https://learn.microsoft.com/en-us/security-copilot/) +- [Entra ID Registration](https://learn.microsoft.com/en-us/azure/active-directory/develop/quickstart-register-app) +- [Security Copilot API Documentation](https://learn.microsoft.com/en-us/copilot/security/activity-export-api) + diff --git a/Security Copilot APIs/ExportAdminAPI/SecurityCopilotExportAdminAPIs.ps1 b/Security Copilot APIs/ExportAdminAPI/SecurityCopilotExportAdminAPIs.ps1 new file mode 100644 index 00000000..5e281691 --- /dev/null +++ b/Security Copilot APIs/ExportAdminAPI/SecurityCopilotExportAdminAPIs.ps1 @@ -0,0 +1,164 @@ +# Get Bearer Token from Entra ID using Enterprise App +$tenantId = "" +$clientId = "" +$clientSecret = "" +$scope = "https://api.securitycopilot.microsoft.com/.default" # Security Copilot API scope + +# Construct the token request +$body = @{ + client_id = $clientId + scope = $scope + client_secret = $clientSecret + grant_type = "client_credentials" +} +$tokenUrl = "https://login.microsoftonline.com/$tenantId/oauth2/v2.0/token" + +$response = Invoke-RestMethod -Uri $tokenUrl -Method Post -Body $body -ContentType "application/x-www-form-urlencoded" +$bearerToken = $response.access_token + +# Calculate date range for the last week +$endDate = (Get-Date).ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffZ") +$startDate = (Get-Date).AddDays(-365).ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffZ") + +# Function to fetch and export Security Copilot data +function Get-SecurityCopilotData { + param( + [Parameter(Mandatory=$true)] + [ValidateSet("prompts", "evaluations")] + [string]$ResourceType, + + [Parameter(Mandatory=$true)] + [string]$BearerToken, + + [Parameter(Mandatory=$true)] + [string]$StartDate, + + [Parameter(Mandatory=$true)] + [string]$EndDate, + + [int]$MaxRetries = 5, + + [int]$InitialWaitTime = 60 + ) + + # Build API URL with date filters + $apiUrl = "https://api.securitycopilot.microsoft.com/exports/$ResourceType`?startDate=$([System.Uri]::EscapeDataString($StartDate))&endDate=$([System.Uri]::EscapeDataString($EndDate))" + + Write-Host "`n-------------------------------------------------------------" -ForegroundColor DarkGray + Write-Host "[$($ResourceType.ToUpper())] Fetching data from $StartDate to $EndDate" -ForegroundColor Magenta + Write-Host "-------------------------------------------------------------" -ForegroundColor DarkGray + Write-Host "[API CALL] " -ForegroundColor Yellow -NoNewline + Write-Host "$apiUrl" -ForegroundColor Cyan + Write-Host "-------------------------------------------------------------" -ForegroundColor DarkGray + + $headers = @{ + "Authorization" = "Bearer $BearerToken" + "Content-Type" = "application/json" + } + $continuationToken = $null + $allData = @() + $retryCount = 0 + $waitTime = $InitialWaitTime + + do { + try { + $apiResponse = Invoke-RestMethod -Uri $apiUrl -Method Get -Headers $headers + $retryCount = 0 # Reset retry count on successful call + } catch { + $statusCode = $_.Exception.Response.StatusCode.value__ + if ($statusCode -eq 429) { + $retryCount++ + if ($retryCount -le $MaxRetries) { + Write-Host "`n[WARNING] Rate limit exceeded. Attempt $retryCount of $MaxRetries" -ForegroundColor Yellow + Write-Host "[INFO] Waiting for $waitTime seconds before retrying..." -ForegroundColor Cyan + Start-Sleep -Seconds $waitTime + $waitTime = $waitTime * 2 # Exponential back-off + continue + } else { + Write-Host "`n[ERROR] Max retries reached. Exiting..." -ForegroundColor Red + break + } + } else { + Write-Host "`n[ERROR] $($_.Exception.Message)" -ForegroundColor Red + break + } + } + + $waitTime = $InitialWaitTime + + # Accumulate data from each response + if ($apiResponse.$ResourceType) { + $allData += $apiResponse.$ResourceType + + # Display each prompt in a fancy way + if ($ResourceType -eq "prompts") { + foreach ($prompt in $apiResponse.$ResourceType) { + Write-Host "`n -----------------------------------------------------------" -ForegroundColor DarkCyan + Write-Host " | " -ForegroundColor DarkCyan -NoNewline + Write-Host "Session ID : " -ForegroundColor Gray -NoNewline + Write-Host "$($prompt.sessionId)" -ForegroundColor White + Write-Host " | " -ForegroundColor DarkCyan -NoNewline + Write-Host "Prompt ID : " -ForegroundColor Gray -NoNewline + Write-Host "$($prompt.promptId)" -ForegroundColor White + Write-Host " | " -ForegroundColor DarkCyan -NoNewline + Write-Host "Source : " -ForegroundColor Gray -NoNewline + Write-Host "$($prompt.source)" -ForegroundColor Cyan + Write-Host " | " -ForegroundColor DarkCyan -NoNewline + Write-Host "Prompt Type : " -ForegroundColor Gray -NoNewline + Write-Host "$($prompt.promptType)" -ForegroundColor Yellow + + # If prompt type is "prompt", display the content (no skill name) + if ($prompt.promptType -eq "prompt") { + Write-Host " | " -ForegroundColor DarkCyan -NoNewline + Write-Host "Content : " -ForegroundColor Gray -NoNewline + Write-Host "$($prompt.content)" -ForegroundColor Green + } + # If prompt type is "skill", display skill name and inputs + elseif ($prompt.promptType -eq "skill") { + Write-Host " | " -ForegroundColor DarkCyan -NoNewline + Write-Host "Skill Name : " -ForegroundColor Gray -NoNewline + Write-Host "$($prompt.skillName)" -ForegroundColor Magenta + Write-Host " | " -ForegroundColor DarkCyan -NoNewline + Write-Host "Inputs : " -ForegroundColor Gray -NoNewline + Write-Host "$($prompt.inputs)" -ForegroundColor Cyan + } + + Write-Host " -----------------------------------------------------------" -ForegroundColor DarkCyan + } + } + } + + Write-Host "`n[INFO] Fetched $($apiResponse.$ResourceType.Count) $ResourceType in this batch" -ForegroundColor Cyan + + # Stop if no data returned + if ($null -eq $apiResponse.$ResourceType -or $apiResponse.$ResourceType.Count -eq 0) { + Write-Host "`n[WARNING] No more $ResourceType to fetch" -ForegroundColor Yellow + break + } + + $continuationToken = $apiResponse.sessionsContinuationToken + if ($null -ne $continuationToken) { + $apiUrl = "https://api.securitycopilot.microsoft.com/exports/$ResourceType`?startDate=$([System.Uri]::EscapeDataString($StartDate))&endDate=$([System.Uri]::EscapeDataString($EndDate))&continuationToken=$([System.Uri]::EscapeDataString($continuationToken))" + } + + Write-Host "[PROGRESS] Total $ResourceType fetched so far: $($allData.Count)" -ForegroundColor DarkGray + + Start-Sleep -Seconds 1 + } while ($null -ne $continuationToken) + + # Export all data to CSV + $outputFile = "$($ResourceType)_export.csv" + $allData | Export-Csv -Path $outputFile -NoTypeInformation -Encoding UTF8 + + Write-Host "`n-------------------------------------------------------------" -ForegroundColor DarkGray + Write-Host "[SUCCESS] Exported $($allData.Count) $ResourceType to $outputFile" -ForegroundColor Green + Write-Host "-------------------------------------------------------------`n" -ForegroundColor DarkGray + + return $allData +} + +# Fetch prompts +$allPrompts = Get-SecurityCopilotData -ResourceType "prompts" -BearerToken $bearerToken -StartDate $startDate -EndDate $endDate + +# Fetch evaluations +$allEvaluations = Get-SecurityCopilotData -ResourceType "evaluations" -BearerToken $bearerToken -StartDate $startDate -EndDate $endDate \ No newline at end of file diff --git a/Security Copilot APIs/GraphAPI/README.md b/Security Copilot APIs/GraphAPI/README.md new file mode 100644 index 00000000..a5e28a16 --- /dev/null +++ b/Security Copilot APIs/GraphAPI/README.md @@ -0,0 +1,237 @@ +# Security Copilot Graph API + +A PowerShell script to interact with Microsoft Security Copilot using the Microsoft Graph API for managing workspaces, sessions, prompts, and evaluations. + +## Overview + +This script demonstrates how to authenticate with Microsoft Security Copilot's Graph API using delegated user authentication and perform common operations such as listing plugins, creating sessions, submitting prompts, and evaluating responses. It's useful for automation, testing, and integrating Security Copilot capabilities into custom workflows. + +## Features + +- **Delegated Authentication**: Uses interactive login with MSAL for user-based authentication +- **Plugin Management**: Retrieve and display all available plugins and their status +- **Session Management**: Create new Security Copilot sessions programmatically +- **Prompt Submission**: Submit prompts to sessions and receive prompt IDs +- **Evaluation Workflow**: Start evaluations and monitor their completion status +- **Formatted Console Output**: Color-coded display with clear visual sections +- **Real-time Monitoring**: Polls evaluation status until completion +- **Response Display**: Shows the final evaluation results + +## Prerequisites + +- PowerShell 5.1 or higher +- MSAL.PS PowerShell module +- Microsoft Security Copilot instance +- Entra ID account with appropriate permissions +- Microsoft Graph API permissions: + - `SecurityCopilotWorkspaces.ReadWrite.All` + +## Setup + +### 1. Install MSAL.PS Module + +Open PowerShell and install the MSAL.PS module: + +```powershell +Install-Module -Name MSAL.PS -Scope CurrentUser +``` + +### 2. Register Application in Entra ID (Optional for Delegated Flow) + +For delegated authentication, you can use the public client app registration or create your own: + +1. Navigate to **Azure Active Directory** > **App registrations** > **New registration** +2. Name your application (e.g., "Security Copilot Graph Client") +3. Set **Platform** to **Mobile and desktop applications** +4. Add redirect URI: `http://localhost` or `https://login.microsoftonline.com/common/oauth2/nativeclient` +5. Note the **Application (client) ID** and **Directory (tenant) ID** + +
+ +
+ +### 3. Configure API Permissions + +1. Go to **API permissions** > **Add a permission** +2. Select **Microsoft Graph** > **Delegated permissions** +3. Add `SecurityCopilotWorkspaces.ReadWrite.All` +4. Grant admin consent if required by your organization + +
+ +
+ +### 4. Update Script Variables + +Edit the script and replace the following variables with your values: + +```powershell +$TenantId = "YOUR-TENANT-ID" +$ClientId = "YOUR-CLIENT-ID" +$WorkspaceId = "default" # or your specific workspace ID +``` + +## Usage + +Run the script in PowerShell: + +```powershell +.\SecurityCopilotGraphApi.ps1 +``` + +The script will: +1. Prompt for interactive authentication (browser popup) +2. Retrieve and display all available plugins with their status +3. Create a new session named "Who am I" +4. Submit the prompt "Who am I?" +5. Start an evaluation of the prompt +6. Monitor the evaluation status until completion +7. Display the final response + +## Configuration + +### Workspace ID + +By default, the script uses `"default"` as the workspace ID. To use a specific workspace: + +```powershell +$WorkspaceId = "your-workspace-guid" +``` + +### Authentication Scopes + +The script requests the following scope: + +```powershell +-Scopes "SecurityCopilotWorkspaces.ReadWrite.All" +``` + +You can modify this based on your permission requirements. + +### Polling Interval + +Adjust the evaluation monitoring frequency: + +```powershell +Start-Sleep -Milliseconds 500 # Check every 500ms +``` + +## API Operations + +The script demonstrates the following Graph API endpoints: + +### 1. List Plugins + +``` +GET https://graph.microsoft.com/beta/security/securityCopilot/workspaces/{workspaceId}/plugins +``` + +Returns all available plugins (skills) and their enabled status. + +### 2. Create Session + +``` +POST https://graph.microsoft.com/beta/security/securityCopilot/workspaces/{workspaceId}/sessions +``` + +Creates a new Security Copilot session with a display name. + +### 3. Submit Prompt + +``` +POST https://graph.microsoft.com/beta/security/securityCopilot/workspaces/{workspaceId}/sessions/{sessionId}/prompts +``` + +Submits a prompt to an existing session. + +### 4. Start Evaluation + +``` +POST https://graph.microsoft.com/beta/security/securityCopilot/workspaces/{workspaceId}/sessions/{sessionId}/prompts/{promptId}/evaluations +``` + +Initiates evaluation of a submitted prompt. + +### 5. Check Evaluation Status + +``` +GET https://graph.microsoft.com/beta/security/securityCopilot/workspaces/{workspaceId}/sessions/{sessionId}/prompts/{promptId}/evaluations/{evaluationId} +``` + +Retrieves the current state and results of an evaluation. + + +## Example Output + +
+ +
+ + +## Error Handling + +The script includes basic error handling. Common issues: + +- **Authentication Failures**: Check tenant ID, client ID, and permissions +- **API Errors**: Ensure you have proper Graph API permissions +- **Module Not Found**: Install MSAL.PS module +- **Workspace Access**: Verify you have access to the specified workspace + + +## Security Best Practices + +1. **Token Management**: + - MSAL.PS handles token caching automatically + - Tokens are stored securely in user profile + - Consider token lifetime for long-running scripts + +2. **Principle of Least Privilege**: + - Request only necessary scopes + - Use read-only scopes when modification isn't needed + +3. **Data Protection**: + - Be cautious with sensitive data in prompts + - Implement logging controls for compliance + - Consider data residency requirements + + +## Troubleshooting + +### Module Import Errors +```powershell +Import-Module MSAL.PS -Force +``` + +### Authentication Popup Issues +- Ensure your browser allows popups +- Check if conditional access policies block the sign-in +- Try using `-DeviceCode` parameter for MSAL authentication + +### Permission Errors +- Verify the required permissions are granted +- Ensure admin consent is provided if required +- Check if the user has access to the workspace + +### API Version Issues +- The script uses `/beta` endpoints +- Some features may change; consult the latest documentation + + +## License + +This project is provided as-is for educational and demonstration purposes. + +## Contributing + +Contributions, issues, and feature requests are welcome! + +## Author + +[Mario Cuomo](https://www.linkedin.com/in/mariocuomo/) + +## References + +- [Microsoft Security Copilot Documentation](https://learn.microsoft.com/en-us/security-copilot/) +- [Microsoft Graph API Documentation](https://learn.microsoft.com/en-us/graph/) + + diff --git a/Security Copilot APIs/GraphAPI/SecurityCopilotGraphApi.ps1 b/Security Copilot APIs/GraphAPI/SecurityCopilotGraphApi.ps1 new file mode 100644 index 00000000..37910431 --- /dev/null +++ b/Security Copilot APIs/GraphAPI/SecurityCopilotGraphApi.ps1 @@ -0,0 +1,107 @@ +Import-Module MSAL.PS +Write-Host "`n=============================================================" -ForegroundColor Magenta +Write-Host " Microsoft Security Copilot API Demo" -ForegroundColor Magenta +Write-Host "=============================================================`n" -ForegroundColor Magenta + +# CONFIGURATION +$TenantId = "" +$ClientId = "" +$WorkspaceId = "default" + +Write-Host "[AUTH] Initiating delegated authentication..." -ForegroundColor Yellow +$tokenResponse = Get-MsalToken -ClientId $ClientId ` + -TenantId $TenantId ` + -Scopes "SecurityCopilotWorkspaces.ReadWrite.All" ` + -Interactive + +$accessToken = $tokenResponse.AccessToken +Write-Host "[SUCCESS] Authenticated as: " -ForegroundColor Green -NoNewline +Write-Host "$($tokenResponse.Account.Username)" -ForegroundColor Cyan + +## RETRIEVE ALL THE PLUGINS +Write-Host "`n-------------------------------------------------------------" -ForegroundColor DarkGray +Write-Host "[PLUGINS] Retrieving Plugin List" -ForegroundColor Magenta +Write-Host "-------------------------------------------------------------" -ForegroundColor DarkGray +$uri = "https://graph.microsoft.com/beta/security/securityCopilot/workspaces/$WorkspaceId/plugins" +$response = Invoke-RestMethod -Uri $uri -Method GET -Headers @{ Authorization = "Bearer $accessToken" } +foreach ($plugin in $response.value) { + Write-Host "`n - " -ForegroundColor DarkGray -NoNewline + Write-Host "$($plugin.displayName)" -ForegroundColor Cyan + Write-Host " Status: " -ForegroundColor DarkGray -NoNewline + Write-Host $(if ($plugin.isEnabled) { "Enabled" } else { "Disabled" }) -ForegroundColor $(if ($plugin.isEnabled) { 'Green' } else { 'Yellow' }) +} + + + +## CREATE A SESSION +Write-Host "`n-------------------------------------------------------------" -ForegroundColor DarkGray +Write-Host "[SESSION] Creating Session: 'Who am I'" -ForegroundColor Magenta +Write-Host "-------------------------------------------------------------" -ForegroundColor DarkGray +$uri = "https://graph.microsoft.com/beta/security/securityCopilot/workspaces/$WorkspaceId/sessions" +$body = @{ + displayName = "Who am I" +} | ConvertTo-Json +$response = Invoke-RestMethod -Uri $uri -Method POST -Headers @{ + Authorization = "Bearer $accessToken" + "Content-Type" = "application/json" +} -Body $body +Write-Host "[SUCCESS] Session created with ID: " -ForegroundColor Green -NoNewline +Write-Host "$($response.id)" -ForegroundColor Cyan +$sessionId = $response.id + + +## SUBMITTING A PROMPT TO THE SESSION +Write-Host "`n-------------------------------------------------------------" -ForegroundColor DarkGray +Write-Host "[PROMPT] Submitting Prompt: 'Who am I?'" -ForegroundColor Magenta +Write-Host "-------------------------------------------------------------" -ForegroundColor DarkGray +$uri = "https://graph.microsoft.com/beta/security/securityCopilot/workspaces/$WorkspaceId/sessions/$sessionId/prompts" +$body = @{ + content = "Who am I?" + type = "prompt" +} | ConvertTo-Json +$response = Invoke-RestMethod -Uri $uri -Method POST -Headers @{ + Authorization = "Bearer $accessToken" + "Content-Type" = "application/json" +} -Body $body +Write-Host "[SUCCESS] Prompt submitted with ID: " -ForegroundColor Green -NoNewline +Write-Host "$($response.id)" -ForegroundColor Cyan +$promptId = $response.id + +## EVALUATING THE PROMPT +Write-Host "`n-------------------------------------------------------------" -ForegroundColor DarkGray +Write-Host "[EVALUATION] Starting Prompt Evaluation" -ForegroundColor Magenta +Write-Host "-------------------------------------------------------------" -ForegroundColor DarkGray +$uri = "https://graph.microsoft.com/beta/security/securityCopilot/workspaces/$WorkspaceId/sessions/$sessionId/prompts/$promptId/evaluations" +$body = @{ +} | ConvertTo-Json +$response = Invoke-RestMethod -Uri $uri -Method POST -Headers @{ + Authorization = "Bearer $accessToken" + "Content-Type" = "application/json" +} -Body $body +Write-Host "[SUCCESS] Evaluation submitted with ID: " -ForegroundColor Green -NoNewline +Write-Host "$($response.id)" -ForegroundColor Cyan +$evaluationId = $response.id + +## PRINTING THE EVALUATION STATUS UNTIL COMPLETED +Write-Host "`n[MONITOR] Checking evaluation status..." -ForegroundColor Yellow +$state = "unknown" +while ($state -ne "completed") { + $uri = "https://graph.microsoft.com/beta/security/securityCopilot/workspaces/$WorkspaceId/sessions/$sessionId/prompts/$promptId/evaluations/$evaluationId" + $response = Invoke-RestMethod -Uri $uri -Method GET -Headers @{ + Authorization = "Bearer $accessToken" + } + $state = $response.state + Write-Host " > Current state: " -ForegroundColor DarkGray -NoNewline + Write-Host "$state" -ForegroundColor Yellow + Start-Sleep -Milliseconds 500 +} +Write-Host "`n[SUCCESS] Evaluation completed!" -ForegroundColor Green + +## RETRIEVING THE EVALUATION RESULTS +Write-Host "`n-------------------------------------------------------------" -ForegroundColor DarkGray +Write-Host "[RESPONSE] Result" -ForegroundColor Magenta +Write-Host "-------------------------------------------------------------" -ForegroundColor DarkGray +Write-Host "$($response.result.content)" -ForegroundColor Cyan +Write-Host "`n=============================================================" -ForegroundColor Magenta +Write-Host " Demo Complete" -ForegroundColor Magenta +Write-Host "=============================================================`n" -ForegroundColor Magenta diff --git a/Security Copilot APIs/README.md b/Security Copilot APIs/README.md new file mode 100644 index 00000000..e8f163f4 --- /dev/null +++ b/Security Copilot APIs/README.md @@ -0,0 +1,27 @@ +## Security Copilot API Examples +This folder provides sample implementations and usage examples for Microsoft Security Copilot APIs, designed to help developers and administrators integrate advanced security capabilities into their workflows. + +### Overview +Security Copilot APIs enable organizations to leverage AI-driven security insights and automation. This folder includes examples for two key APIs: + +- [Export Admin API](https://github.com/mariocuomo/Security-Copilot/tree/main/Security%20Copilot%20APIs/ExportAdminAPI) +- [Security Graph API](https://github.com/mariocuomo/Security-Copilot/tree/main/Security%20Copilot%20APIs/GraphAPI) + + +### Export Admin API +The Export Admin API allows workspace administrators to export prompts and prompt responses in a paginated format. This is particularly useful for: + +- **Auditing prompt usage** +- **Analyzing response patterns** +- **Maintaining compliance records** + +### Security Graph API +The Security Graph API provides programmatic access to core Security Copilot resources, enabling developers to manage and interact with workspaces, sessions, prompts, evaluations, and plugins. This API is ideal for building integrations, automating workflows, and extending Security Copilot capabilities. + +- **Automate session creation and prompt execution** +- **Retrieve and analyze prompt responses** +- **Evaluate prompt performance and accuracy** + +### Contributing + +Contributions are welcome! Please submit a pull request or open an issue for any improvements or bug fixes.