├── .gitignore ├── IMDSSample-windows.cpp ├── IMDSSample.cs ├── IMDSSample.js ├── IMDSSample.pl ├── IMDSSample.ps1 ├── IMDSSample.py ├── IMDSSample.rb ├── IMDSSample.sh ├── IMDSSample.vb ├── LICENSE ├── README.md ├── SECURITY.md ├── imdssample.go ├── imdssample.java └── user-data-arm-template ├── README.md ├── azuredeploy.json └── azuredeploy.parameters.json /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.suo 8 | *.user 9 | *.userosscache 10 | *.sln.docstates 11 | 12 | # User-specific files (MonoDevelop/Xamarin Studio) 13 | *.userprefs 14 | 15 | # Build results 16 | [Dd]ebug/ 17 | [Dd]ebugPublic/ 18 | [Rr]elease/ 19 | [Rr]eleases/ 20 | x64/ 21 | x86/ 22 | bld/ 23 | [Bb]in/ 24 | [Oo]bj/ 25 | [Ll]og/ 26 | 27 | # Visual Studio 2015 cache/options directory 28 | .vs/ 29 | # Uncomment if you have tasks that create the project's static files in wwwroot 30 | #wwwroot/ 31 | 32 | # MSTest test Results 33 | [Tt]est[Rr]esult*/ 34 | [Bb]uild[Ll]og.* 35 | 36 | # NUNIT 37 | *.VisualState.xml 38 | TestResult.xml 39 | 40 | # Build Results of an ATL Project 41 | [Dd]ebugPS/ 42 | [Rr]eleasePS/ 43 | dlldata.c 44 | 45 | # .NET Core 46 | project.lock.json 47 | project.fragment.lock.json 48 | artifacts/ 49 | **/Properties/launchSettings.json 50 | 51 | *_i.c 52 | *_p.c 53 | *_i.h 54 | *.ilk 55 | *.meta 56 | *.obj 57 | *.pch 58 | *.pdb 59 | *.pgc 60 | *.pgd 61 | *.rsp 62 | *.sbr 63 | *.tlb 64 | *.tli 65 | *.tlh 66 | *.tmp 67 | *.tmp_proj 68 | *.log 69 | *.vspscc 70 | *.vssscc 71 | .builds 72 | *.pidb 73 | *.svclog 74 | *.scc 75 | 76 | # Chutzpah Test files 77 | _Chutzpah* 78 | 79 | # Visual C++ cache files 80 | ipch/ 81 | *.aps 82 | *.ncb 83 | *.opendb 84 | *.opensdf 85 | *.sdf 86 | *.cachefile 87 | *.VC.db 88 | *.VC.VC.opendb 89 | 90 | # Visual Studio profiler 91 | *.psess 92 | *.vsp 93 | *.vspx 94 | *.sap 95 | 96 | # TFS 2012 Local Workspace 97 | $tf/ 98 | 99 | # Guidance Automation Toolkit 100 | *.gpState 101 | 102 | # ReSharper is a .NET coding add-in 103 | _ReSharper*/ 104 | *.[Rr]e[Ss]harper 105 | *.DotSettings.user 106 | 107 | # JustCode is a .NET coding add-in 108 | .JustCode 109 | 110 | # TeamCity is a build add-in 111 | _TeamCity* 112 | 113 | # DotCover is a Code Coverage Tool 114 | *.dotCover 115 | 116 | # Visual Studio code coverage results 117 | *.coverage 118 | *.coveragexml 119 | 120 | # NCrunch 121 | _NCrunch_* 122 | .*crunch*.local.xml 123 | nCrunchTemp_* 124 | 125 | # MightyMoose 126 | *.mm.* 127 | AutoTest.Net/ 128 | 129 | # Web workbench (sass) 130 | .sass-cache/ 131 | 132 | # Installshield output folder 133 | [Ee]xpress/ 134 | 135 | # DocProject is a documentation generator add-in 136 | DocProject/buildhelp/ 137 | DocProject/Help/*.HxT 138 | DocProject/Help/*.HxC 139 | DocProject/Help/*.hhc 140 | DocProject/Help/*.hhk 141 | DocProject/Help/*.hhp 142 | DocProject/Help/Html2 143 | DocProject/Help/html 144 | 145 | # Click-Once directory 146 | publish/ 147 | 148 | # Publish Web Output 149 | *.[Pp]ublish.xml 150 | *.azurePubxml 151 | # TODO: Comment the next line if you want to checkin your web deploy settings 152 | # but database connection strings (with potential passwords) will be unencrypted 153 | *.pubxml 154 | *.publishproj 155 | 156 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 157 | # checkin your Azure Web App publish settings, but sensitive information contained 158 | # in these scripts will be unencrypted 159 | PublishScripts/ 160 | 161 | # NuGet Packages 162 | *.nupkg 163 | # The packages folder can be ignored because of Package Restore 164 | **/packages/* 165 | # except build/, which is used as an MSBuild target. 166 | !**/packages/build/ 167 | # Uncomment if necessary however generally it will be regenerated when needed 168 | #!**/packages/repositories.config 169 | # NuGet v3's project.json files produces more ignorable files 170 | *.nuget.props 171 | *.nuget.targets 172 | 173 | # Microsoft Azure Build Output 174 | csx/ 175 | *.build.csdef 176 | 177 | # Microsoft Azure Emulator 178 | ecf/ 179 | rcf/ 180 | 181 | # Windows Store app package directories and files 182 | AppPackages/ 183 | BundleArtifacts/ 184 | Package.StoreAssociation.xml 185 | _pkginfo.txt 186 | 187 | # Visual Studio cache files 188 | # files ending in .cache can be ignored 189 | *.[Cc]ache 190 | # but keep track of directories ending in .cache 191 | !*.[Cc]ache/ 192 | 193 | # Others 194 | ClientBin/ 195 | ~$* 196 | *~ 197 | *.dbmdl 198 | *.dbproj.schemaview 199 | *.jfm 200 | *.pfx 201 | *.publishsettings 202 | orleans.codegen.cs 203 | 204 | # Since there are multiple workflows, uncomment next line to ignore bower_components 205 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 206 | #bower_components/ 207 | 208 | # RIA/Silverlight projects 209 | Generated_Code/ 210 | 211 | # Backup & report files from converting an old project file 212 | # to a newer Visual Studio version. Backup files are not needed, 213 | # because we have git ;-) 214 | _UpgradeReport_Files/ 215 | Backup*/ 216 | UpgradeLog*.XML 217 | UpgradeLog*.htm 218 | 219 | # SQL Server files 220 | *.mdf 221 | *.ldf 222 | *.ndf 223 | 224 | # Business Intelligence projects 225 | *.rdl.data 226 | *.bim.layout 227 | *.bim_*.settings 228 | 229 | # Microsoft Fakes 230 | FakesAssemblies/ 231 | 232 | # GhostDoc plugin setting file 233 | *.GhostDoc.xml 234 | 235 | # Node.js Tools for Visual Studio 236 | .ntvs_analysis.dat 237 | node_modules/ 238 | 239 | # Typescript v1 declaration files 240 | typings/ 241 | 242 | # Visual Studio 6 build log 243 | *.plg 244 | 245 | # Visual Studio 6 workspace options file 246 | *.opt 247 | 248 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 249 | *.vbw 250 | 251 | # Visual Studio LightSwitch build output 252 | **/*.HTMLClient/GeneratedArtifacts 253 | **/*.DesktopClient/GeneratedArtifacts 254 | **/*.DesktopClient/ModelManifest.xml 255 | **/*.Server/GeneratedArtifacts 256 | **/*.Server/ModelManifest.xml 257 | _Pvt_Extensions 258 | 259 | # Paket dependency manager 260 | .paket/paket.exe 261 | paket-files/ 262 | 263 | # FAKE - F# Make 264 | .fake/ 265 | 266 | # JetBrains Rider 267 | .idea/ 268 | *.sln.iml 269 | 270 | # CodeRush 271 | .cr/ 272 | 273 | # Python Tools for Visual Studio (PTVS) 274 | __pycache__/ 275 | *.pyc 276 | 277 | # Cake - Uncomment if you are using it 278 | # tools/** 279 | # !tools/packages.config 280 | 281 | # Telerik's JustMock configuration file 282 | *.jmconfig 283 | 284 | # BizTalk build output 285 | *.btp.cs 286 | *.btm.cs 287 | *.odx.cs 288 | *.xsd.cs 289 | -------------------------------------------------------------------------------- /IMDSSample-windows.cpp: -------------------------------------------------------------------------------- 1 | // build using 2 | // cl /EHsc imds_windows.cpp 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | #pragma comment(lib,"winhttp.lib") 10 | 11 | const wchar_t* MetadataRequiredHeader = L"metadata: true"; 12 | 13 | void GetMetadata(LPCWSTR serverName, WORD port, LPCWSTR url) 14 | { 15 | LPSTR pszOutBuffer = NULL; 16 | HINTERNET hSession = NULL, hConnect = NULL, hRequest = NULL; 17 | 18 | try 19 | { 20 | // ======================================================================================== 21 | // Setup connection 22 | // ======================================================================================== 23 | hSession = WinHttpOpen(L"WinHTTP connection from WS to IMDS", 24 | WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, 25 | WINHTTP_NO_PROXY_NAME, 26 | WINHTTP_NO_PROXY_BYPASS, 27 | /* dwFlags */ 0); 28 | if (hSession == NULL) 29 | throw L"Failed to create session"; 30 | 31 | hConnect = WinHttpConnect(hSession, serverName, port, /* dwReserved */ 0); 32 | if(!hConnect) 33 | { 34 | throw L"Failed to connect"; 35 | } 36 | 37 | hRequest = WinHttpOpenRequest(hConnect, L"GET", url, 38 | NULL, WINHTTP_NO_REFERER, 39 | WINHTTP_DEFAULT_ACCEPT_TYPES, 40 | 0); 41 | 42 | if(!hRequest) throw L"Failed to open request"; 43 | 44 | if(!WinHttpAddRequestHeaders(hRequest, MetadataRequiredHeader, -1L, WINHTTP_ADDREQ_FLAG_ADD)) 45 | throw L" Failed in WinHttpAddRequestHeaders"; 46 | 47 | if(!WinHttpSendRequest(hRequest, 48 | WINHTTP_NO_ADDITIONAL_HEADERS, /* dwHeadersLength */ 0, 49 | WINHTTP_NO_REQUEST_DATA, /* dwOptionalLength */ 0, 50 | /* dwTotalLength */ 0, /* dwContext */ 0)) 51 | throw L"Failed in WinHttpSendRequest"; 52 | 53 | // ======================================================================================== 54 | // Receive response and headers 55 | // ======================================================================================== 56 | DWORD httpStatusCode = 0; 57 | DWORD httpStatusSize = sizeof(httpStatusCode); 58 | if(!WinHttpReceiveResponse(hRequest, /* lpReserved */ NULL)) 59 | { 60 | throw L"Failed in WinHttpReceiveReponse"; 61 | } 62 | 63 | if(!WinHttpQueryHeaders(hRequest, 64 | WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER, 65 | WINHTTP_HEADER_NAME_BY_INDEX, 66 | &httpStatusCode, &httpStatusSize, WINHTTP_NO_HEADER_INDEX)) 67 | { 68 | throw L"Failed in WinHttpQueryHeaders"; 69 | } 70 | 71 | std::wcout << L"Status code: " << httpStatusCode << std::endl; 72 | 73 | wchar_t contentType[256]; 74 | DWORD headerLength = sizeof(contentType); 75 | if(!WinHttpQueryHeaders(hRequest, 76 | WINHTTP_QUERY_CONTENT_TYPE, 77 | NULL, 78 | contentType, 79 | &headerLength, 80 | WINHTTP_NO_HEADER_INDEX)) 81 | { 82 | throw L"Failed inWinHttpQueryHeaders"; 83 | } 84 | 85 | 86 | DWORD dwSize; 87 | WinHttpQueryHeaders(hRequest, 88 | WINHTTP_QUERY_RAW_HEADERS_CRLF, 89 | WINHTTP_HEADER_NAME_BY_INDEX, NULL, 90 | &dwSize, WINHTTP_NO_HEADER_INDEX); 91 | if(GetLastError() == ERROR_INSUFFICIENT_BUFFER) 92 | { 93 | auto lpOutBuffer = new wchar_t[dwSize/sizeof(wchar_t)]; 94 | 95 | // Now, use WinHttpQueryHeaders to retrieve the header. 96 | if(!WinHttpQueryHeaders(hRequest, 97 | WINHTTP_QUERY_RAW_HEADERS_CRLF, 98 | WINHTTP_HEADER_NAME_BY_INDEX, 99 | lpOutBuffer, &dwSize, 100 | WINHTTP_NO_HEADER_INDEX)) 101 | { 102 | throw L"Failed in WinHttpQueryHeaders - All Headers"; 103 | } 104 | 105 | std::wcout << L"=============================================================" << std::endl; 106 | std::wcout << lpOutBuffer; 107 | std::wcout << L"=============================================================" << std::endl; 108 | 109 | delete [] lpOutBuffer; 110 | } 111 | 112 | // ======================================================================================== 113 | // Receive data from server and print 114 | // ======================================================================================== 115 | // Keep checking for data until there is nothing left. 116 | dwSize = 0; 117 | do 118 | { 119 | // Check for available data. 120 | if(!WinHttpQueryDataAvailable(hRequest, &dwSize)) 121 | { 122 | throw L"Failed in WinHttpQueryDataAvailable"; 123 | } 124 | 125 | // Allocate space for the buffer. 126 | pszOutBuffer = new char[dwSize + 1]; 127 | if(pszOutBuffer == NULL) 128 | { 129 | throw L"Failed to allocate memory for pszOutBuffer."; 130 | } 131 | 132 | // Read the data. 133 | ZeroMemory(pszOutBuffer, dwSize + 1); 134 | 135 | DWORD dwDownloaded = 0; 136 | if(!WinHttpReadData(hRequest, (LPVOID)pszOutBuffer, dwSize, &dwDownloaded)) 137 | { 138 | throw L"Failed in WinHttpReadData"; 139 | } 140 | 141 | // this is a simple client and we don't parse content-type to find charset 142 | // we assume IMDS always returns utf-8 143 | int wchars_num = ::MultiByteToWideChar(CP_UTF8 , 0 , pszOutBuffer, -1, NULL , 0 ); 144 | wchar_t* wstr = new wchar_t[wchars_num]; 145 | ::MultiByteToWideChar( CP_UTF8 , 0 , pszOutBuffer, -1, wstr , wchars_num ); 146 | 147 | std::wcout << wstr; 148 | 149 | // Free the memory allocated to the buffer. 150 | delete[] wstr; 151 | delete[] pszOutBuffer; 152 | pszOutBuffer = NULL; 153 | 154 | } while (dwSize > 0); 155 | } 156 | catch(LPCWSTR msg) 157 | { 158 | std::wcout << L"ERROR!! " << msg; 159 | } 160 | 161 | if (hRequest) 162 | WinHttpCloseHandle(hRequest); 163 | 164 | if (hConnect) 165 | WinHttpCloseHandle(hConnect); 166 | 167 | if (hSession) 168 | WinHttpCloseHandle(hSession); 169 | 170 | if (pszOutBuffer != NULL) 171 | delete[] pszOutBuffer; 172 | } 173 | 174 | int wmain(int argc, PCWSTR argv[]) 175 | { 176 | GetMetadata(L"169.254.169.254", 80, L"metadata/instance?api-version=2021-02-01"); 177 | 178 | return 0; 179 | } 180 | -------------------------------------------------------------------------------- /IMDSSample.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.IO; 3 | using System.Net; 4 | using System.Net.Http; 5 | using System.Runtime.Serialization; 6 | using System.Runtime.Serialization.Json; 7 | using System.Security.Cryptography; 8 | using System.Security.Cryptography.Pkcs; 9 | using System.Security.Cryptography.X509Certificates; 10 | using System.Text; 11 | using System.Threading.Tasks; 12 | 13 | namespace Samples 14 | { 15 | class IMDSSample 16 | { 17 | const string ImdsServer = "http://169.254.169.254"; 18 | const string InstanceEndpoint = ImdsServer + "/metadata/instance"; 19 | const string AttestedEndpoint = ImdsServer + "/metadata/attested/document"; 20 | const string NonceValue = "123456"; 21 | 22 | static async Task Main(string[] args) 23 | { 24 | // Query /instance metadata 25 | var result = await QueryInstanceEndpoint(); 26 | ParseInstanceResponse(result); 27 | 28 | // Make Attested call and parse the response 29 | result = await QueryAttestedEndpoint(); 30 | ParseAttestedResponse(result); 31 | } 32 | 33 | private static void ParseAttestedResponse(string response) 34 | { 35 | Console.WriteLine("Parsing Attested response"); 36 | AttestedDocument document = (AttestedDocument)SerializeObjectFromJsonString(typeof(AttestedDocument), response); 37 | ValidateCertificate(document); 38 | ValidateAttestedData(document); 39 | } 40 | 41 | private static void ValidateCertificate(AttestedDocument document) 42 | { 43 | try 44 | { 45 | // Build certificate from response 46 | X509Certificate2 cert = new X509Certificate2(System.Text.Encoding.UTF8.GetBytes(document.Signature)); 47 | 48 | // Build certificate chain 49 | X509Chain chain = new X509Chain(); 50 | chain.Build(cert); 51 | 52 | // Print certificate chain information 53 | foreach (X509ChainElement element in chain.ChainElements) 54 | { 55 | Console.WriteLine("Element issuer: {0}", element.Certificate.Issuer); 56 | Console.WriteLine("Element subject: {0}", element.Certificate.Subject); 57 | Console.WriteLine("Element certificate valid until: {0}", element.Certificate.NotAfter); 58 | Console.WriteLine("Element certificate is valid: {0}", element.Certificate.Verify()); 59 | Console.WriteLine("Element error status length: {0}", element.ChainElementStatus.Length); 60 | Console.WriteLine("Element information: {0}", element.Information); 61 | Console.WriteLine("Number of element extensions: {0}{1}", element.Certificate.Extensions.Count, Environment.NewLine); 62 | } 63 | } 64 | catch (CryptographicException ex) 65 | { 66 | Console.WriteLine("Exception: {0}", ex); 67 | } 68 | } 69 | 70 | private static void ValidateAttestedData(AttestedDocument document) 71 | { 72 | try 73 | { 74 | byte[] blob = Convert.FromBase64String(document.Signature); 75 | SignedCms signedCms = new SignedCms(); 76 | signedCms.Decode(blob); 77 | string result = Encoding.UTF8.GetString(signedCms.ContentInfo.Content); 78 | Console.WriteLine("Attested data: {0}", result); 79 | AttestedData data = SerializeObjectFromJsonString(typeof(AttestedData), result) as AttestedData; 80 | if (data.Nonce.Equals(NonceValue)) 81 | { 82 | Console.WriteLine("Nonce values match"); 83 | } 84 | } 85 | catch (Exception ex) 86 | { 87 | Console.WriteLine("Error checking signature blob: '{0}'", ex); 88 | } 89 | } 90 | 91 | private static void ParseInstanceResponse(string response) 92 | { 93 | // Display raw json 94 | Console.WriteLine("Instance response: {0}{1}", response, Environment.NewLine); 95 | } 96 | 97 | private static Task QueryInstanceEndpoint() 98 | { 99 | return QueryImds(InstanceEndpoint, "2021-02-01"); 100 | } 101 | 102 | private static Task QueryAttestedEndpoint() 103 | { 104 | string nonce = "nonce=" + NonceValue; 105 | return QueryImds(AttestedEndpoint, "2021-02-01", nonce); 106 | } 107 | 108 | // Query IMDS server and retrieve JSON result 109 | private static Task QueryImds(string path, string apiVersion) 110 | { 111 | return QueryImds(path, apiVersion, ""); 112 | } 113 | 114 | private static async Task QueryImds(string path, string apiVersion, string otherParams) 115 | { 116 | string imdsUri = path + "?api-version=" + apiVersion; 117 | if (otherParams != null && 118 | !otherParams.Equals(string.Empty)) 119 | { 120 | imdsUri += "&" + otherParams; 121 | } 122 | string jsonResult = string.Empty; 123 | using (var httpClient = new HttpClient()) 124 | { 125 | // IMDS requires bypassing proxies. 126 | WebProxy proxy = new WebProxy(); 127 | HttpClient.DefaultProxy = proxy; 128 | httpClient.DefaultRequestHeaders.Add("Metadata", "True"); 129 | try 130 | { 131 | jsonResult = await httpClient.GetStringAsync(imdsUri); 132 | } 133 | catch (AggregateException ex) 134 | { 135 | // Handle response failures 136 | Console.WriteLine("Request failed: " + ex.GetBaseException()); 137 | } 138 | } 139 | return jsonResult; 140 | } 141 | 142 | private static object SerializeObjectFromJsonString(Type objectType, string json) 143 | { 144 | DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(objectType); 145 | using (MemoryStream memoryStream = new MemoryStream()) 146 | using (StreamWriter writer = new StreamWriter(memoryStream)) 147 | { 148 | // Prepare stream 149 | writer.Write(json); 150 | memoryStream.Position = 0; 151 | 152 | // Serialize object 153 | return jsonSerializer.ReadObject(memoryStream); 154 | } 155 | } 156 | 157 | [DataContract] 158 | public class AttestedDocument 159 | { 160 | [DataMember(Name = "encoding")] 161 | public string Encoding { get; set; } 162 | 163 | [DataMember(Name = "signature")] 164 | public string Signature { get; set; } 165 | } 166 | 167 | [DataContract] 168 | public class AttestedData 169 | { 170 | [DataMember(Name = "nonce")] 171 | public string Nonce { get; set; } 172 | 173 | [DataMember(Name = "vmId")] 174 | public string VmId { get; set; } 175 | 176 | [DataMember(Name = "subscriptionId")] 177 | public string SubscriptionId { get; set; } 178 | 179 | [DataMember(Name = "plan")] public AttestedDataPlanInfo PlanInfo; 180 | 181 | [DataMember(Name = "timeStamp")] public AttestedDataTimeStamp TimeStamp; 182 | } 183 | 184 | [DataContract] 185 | public class AttestedDataPlanInfo 186 | { 187 | [DataMember(Name = "name")] 188 | public string Name { get; set; } 189 | 190 | [DataMember(Name = "product")] 191 | public string Product { get; set; } 192 | 193 | [DataMember(Name = "publisher")] 194 | public string Publisher { get; set; } 195 | } 196 | 197 | [DataContract] 198 | public class AttestedDataTimeStamp 199 | { 200 | [DataMember(Name = "createdOn")] 201 | public string CreatedDate { get; set; } 202 | 203 | [DataMember(Name = "expiresOn")] 204 | public string ExpiryDate { get; set; } 205 | } 206 | } 207 | } 208 | -------------------------------------------------------------------------------- /IMDSSample.js: -------------------------------------------------------------------------------- 1 | // NodeJS Sample for IMDS 2 | 3 | var http = require('http'); 4 | 5 | function JsonQueryIMDS(path, callback) 6 | { 7 | api_version = '2021-02-01'; 8 | imds_server = '169.254.169.254'; 9 | 10 | result = '' 11 | // Set your node js environment variable in .env to bypass proxies. 12 | // Aka NO_PROXY = "*" 13 | http.get({ 14 | host: imds_server, 15 | path: '/metadata' + path + '?api-version=' + api_version, 16 | headers: {'Metadata': 'True'} 17 | }, function(response) { 18 | var statusCode = response.statusCode; 19 | if (statusCode != 200) 20 | { 21 | console.log('Request failed: ') 22 | } 23 | var body = ''; 24 | response.on('data', function(d) { 25 | body += d; 26 | }); 27 | response.on('end', function() { 28 | result = body; 29 | callback(result); 30 | }); 31 | }) 32 | } 33 | 34 | // query /instance metadata 35 | JsonQueryIMDS('/instance', function(result) { 36 | // display raw json 37 | console.log(result); 38 | 39 | // parse json 40 | // .. 41 | }); 42 | -------------------------------------------------------------------------------- /IMDSSample.pl: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env perl 2 | 3 | use strict; 4 | use warnings; 5 | 6 | use HTTP::Tiny; 7 | use JSON; 8 | use Data::Dumper; 9 | 10 | my $md_url = 'http://169.254.169.254/metadata/instance?api-version=2021-02-01'; 11 | my $headers = { Metadata => 'true' }; 12 | 13 | # Proxies must be bypassed when calling Azure IMDS 14 | my $response = HTTP::Tiny->new(proxy => undef)->get($md_url, { headers => $headers }); 15 | my $info = decode_json($response->{ content }); 16 | 17 | print Dumper($info); 18 | 19 | print Dumper($info->{ compute }->{ vmId }); 20 | -------------------------------------------------------------------------------- /IMDSSample.ps1: -------------------------------------------------------------------------------- 1 | $ImdsServer = "http://169.254.169.254" 2 | $InstanceEndpoint = $ImdsServer + "/metadata/instance" 3 | $AttestedEndpoint = $ImdsServer + "/metadata/attested/document" 4 | $NonceValue = "123456" 5 | 6 | # Use of -NoProxy requires use of PowerShell V6 or greater. If you use an older version of PowerShell, 7 | # consider using examples like: 8 | # 9 | # $request = [System.Net.WebRequest]::Create("http://169.254.169.254/metadata/instance?api-version=2019-02-01") 10 | # $request.Proxy = [System.Net.WebProxy]::new() 11 | # $request.Headers.Add("Metadata","True") 12 | # $request.GetResponse() 13 | # 14 | # or: 15 | # 16 | # $Proxy=New-object System.Net.WebProxy 17 | # $WebSession=new-object Microsoft.PowerShell.Commands.WebRequestSession 18 | # $WebSession.Proxy=$Proxy 19 | # Invoke-RestMethod -Headers @{"Metadata"="true"} -Method GET -Uri "http://169.254.169.254/metadata/instance?api-version=2021-02-01" -WebSession $WebSession 20 | 21 | function Query-InstanceEndpoint 22 | { 23 | $uri = $InstanceEndpoint + "?api-version=2021-02-01" 24 | $result = Invoke-RestMethod -Method GET -NoProxy -Uri $uri -Headers @{"Metadata"="True"} 25 | return $result 26 | } 27 | 28 | function Query-AttestedEndpoint 29 | { 30 | $uri = $AttestedEndpoint + "?api-version=2021-02-01&nonce=" + $NonceValue 31 | $result = Invoke-RestMethod -Method GET -NoProxy -Uri $uri -Headers @{"Metadata"="True"} 32 | return $result 33 | } 34 | 35 | function Parse-AttestedResponse 36 | { 37 | param 38 | ( 39 | [PSObject]$response 40 | ) 41 | $signature = $response.signature 42 | Validate-AttestedCertificate $signature 43 | Validate-AttestedData $signature 44 | } 45 | 46 | function Validate-AttestedCertificate 47 | { 48 | param 49 | ( 50 | [string]$signature 51 | ) 52 | $decoded = [System.Convert]::FromBase64String($signature) 53 | $cert = [System.Security.Cryptography.X509Certificates.X509Certificate2]($decoded) 54 | $chain = New-Object -TypeName System.Security.Cryptography.X509Certificates.X509Chain 55 | $result = $chain.Build($cert) 56 | foreach($element in $chain.ChainElements) 57 | { 58 | $element.Certificate | Format-List * 59 | } 60 | } 61 | 62 | function Validate-AttestedData 63 | { 64 | param 65 | ( 66 | [string]$signature 67 | ) 68 | $decoded = [System.Convert]::FromBase64String($signature) 69 | $signedCms = New-Object -TypeName System.Security.Cryptography.Pkcs.SignedCms 70 | $signedCms.Decode($decoded); 71 | $content = [System.Text.Encoding]::UTF8.GetString($signedCms.ContentInfo.Content) 72 | Write-Host "Attested data: " $content 73 | $json = $content | ConvertFrom-Json 74 | $nonce = $json.nonce 75 | if($nonce.Equals($NonceValue)) 76 | { 77 | Write-Host "Nonce values match" 78 | } 79 | } 80 | 81 | # Make Instance call and print the response 82 | $result = Query-InstanceEndpoint 83 | $result | ConvertTo-JSON -Depth 99 84 | 85 | # Make Attested call and parse the response 86 | $result = Query-AttestedEndpoint 87 | Parse-AttestedResponse $result 88 | -------------------------------------------------------------------------------- /IMDSSample.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | import base64 4 | import json 5 | import re 6 | import subprocess 7 | 8 | import requests 9 | 10 | imds_server_base_url = "http://169.254.169.254" 11 | 12 | instance_api_version = "2021-02-01" 13 | instance_endpoint = imds_server_base_url + \ 14 | "/metadata/instance?api-version=" + instance_api_version 15 | 16 | attested_api_version = "2021-02-01" 17 | attested_nonce = "1234576" 18 | attested_endpoint = imds_server_base_url + "/metadata/attested/document?api-version=" + \ 19 | attested_api_version + "&nonce=" + attested_nonce 20 | 21 | # Proxies must be bypassed when calling Azure IMDS 22 | proxies = { 23 | "http": None, 24 | "https": None 25 | } 26 | 27 | 28 | def api_call(endpoint): 29 | headers = {'Metadata': 'True'} 30 | json_obj = requests.get(endpoint, headers=headers, proxies=proxies).json() 31 | return json_obj 32 | 33 | 34 | def main(): 35 | # Instance provider API call 36 | instance_json = api_call(instance_endpoint) 37 | print("Instance provider data:") 38 | pretty_print_json_obj_to_terminal(instance_json) 39 | 40 | # Attested provider API call 41 | attested_json = api_call(attested_endpoint) 42 | print("Attested provider validation:") 43 | attested_signature = attested_json['signature'] 44 | validate_attested_data(attested_signature) 45 | validate_attested_cert(attested_signature) 46 | 47 | 48 | def find_phrase_in_file(filename, phrase): 49 | file = open(filename, "r") 50 | for line in file: 51 | if re.search(phrase, line): 52 | return line 53 | 54 | # Base-64 decode the string 55 | 56 | 57 | def decode_attested_data(attested_signature): 58 | decoded_string = base64.b64decode( 59 | attested_signature).decode('utf-8', 'replace') 60 | return decoded_string 61 | 62 | 63 | def pretty_print_json_obj_to_terminal(json_obj): 64 | print(json.dumps(json_obj, sort_keys=True, indent=4, separators=(',', ': '))) 65 | 66 | # Build the cert chain for validation 67 | 68 | 69 | def validate_attested_cert(attested_signature): 70 | # Dump PKCS7, base64 encoded signature to file. 71 | file = open("signature", "w") 72 | file.write(attested_signature) 73 | file.close() 74 | print("Cert chain validation.") 75 | # We use the subprocess module to call OpenSSL for cert manipulation as PyOpenSSL is missing implementations of these commands. 76 | # First, we base64 decode the signature using the OpenSSL decoder, which works better with subsequent OpenSSL commands than the Python base64 decoder. 77 | subprocess.call( 78 | "openssl enc -base64 -d -A < signature > decoded_signature", shell=True) 79 | # We obtain information about the signer from the decoded signature. 80 | subprocess.call( 81 | "openssl pkcs7 -in decoded_signature -inform DER -print_certs -out signer.pem", shell=True) 82 | # We parse out the intermediate cert URL; then, we download the intermediate cert for verification. 83 | subprocess.call( 84 | "openssl x509 -in signer.pem -text -noout > cert_info", shell=True) 85 | intermediate_cert_url = find_phrase_in_file( 86 | "cert_info", "CA Issuers").split("URI:", 1)[1] 87 | r = requests.get(intermediate_cert_url) 88 | with open('intermediate.cer', 'wb') as f: 89 | f.write(r.content) 90 | subprocess.call( 91 | "openssl x509 -inform der -in intermediate.cer -out intermediate.pem", shell=True) 92 | 93 | # We, finally, verify the complete cert chain. 94 | # DigiCert_Global_Root is our new authority. Both should be trusted for now, but Baltimore is deprecated and can eventually be removed from the check. 95 | # If either statement returns ok then the cert is accepted 96 | subprocess.call( 97 | "openssl verify -verbose -CAfile /etc/ssl/certs/DigiCert_Global_Root.pem -untrusted intermediate.pem signer.pem", shell=True) 98 | subprocess.call( 99 | "openssl verify -verbose -CAfile /etc/ssl/certs/Baltimore_CyberTrust_Root.pem -untrusted intermediate.pem signer.pem", shell=True) 100 | 101 | # Ensure the nonce in the response is the same as the one we supplied. Use similar logic to validate other information such as subscriptionId. 102 | 103 | 104 | def validate_attested_data(attested_signature): 105 | decoded_attested_data = decode_attested_data(attested_signature) 106 | if attested_nonce in decoded_attested_data: 107 | print("Nonce values match.") 108 | 109 | 110 | if __name__ == "__main__": 111 | main() 112 | -------------------------------------------------------------------------------- /IMDSSample.rb: -------------------------------------------------------------------------------- 1 | require 'open-uri' 2 | require 'json' 3 | 4 | url_metadata="http://169.254.169.254/metadata/instance?api-version=2021-02-01" 5 | 6 | # Proxies must be bypassed when calling Azure IMDS 7 | puts open(url_metadata,"Metadata"=>"true", :proxy => nil).read -------------------------------------------------------------------------------- /IMDSSample.sh: -------------------------------------------------------------------------------- 1 | sudo apt-get install curl 2 | sudo apt-get install jq 3 | # NOTE: Proxies must be bypassed using the --noproxy flag when calling Azure IMDS 4 | # Instance call 5 | curl -H Metadata:True --noproxy "*" "http://169.254.169.254/metadata/instance?api-version=2021-02-01&format=json" | jq . 6 | # Make Attested call and extract signature 7 | curl --silent -H Metadata:True --noproxy "*" http://169.254.169.254/metadata/attested/document?api-version=2021-02-01 | jq -r '.["signature"]' > signature 8 | # Decode the signature 9 | base64 -d signature > decodedsignature 10 | #Get PKCS7 format 11 | openssl pkcs7 -in decodedsignature -inform DER -out sign.pk7 12 | # Get Public key out of pkc7 13 | openssl pkcs7 -in decodedsignature -inform DER -print_certs -out signer.pem 14 | #Get the intermediate certificate 15 | curl -so intermediate.cer "$(openssl x509 -in signer.pem -text -noout | grep " CA Issuers -" | awk -FURI: '{print $2}')" 16 | openssl x509 -inform der -in intermediate.cer -out intermediate.pem 17 | #Verify the contents 18 | openssl smime -verify -in sign.pk7 -inform pem -noverify 19 | echo "Verify main certificate subject and issuer" 20 | # Verify the subject name for the main certificate 21 | openssl x509 -noout -subject -in signer.pem 22 | # Verify the issuer for the main certificate 23 | openssl x509 -noout -issuer -in signer.pem 24 | echo "Validate intermediate certificate and issuer " 25 | #Validate the subject name for intermediate certificate 26 | openssl x509 -noout -subject -in intermediate.pem 27 | # Verify the issuer for the intermediate certificate 28 | openssl x509 -noout -issuer -in intermediate.pem 29 | echo "Certificate chain " 30 | # Verify the certificate chain 31 | #If either statement returns ok, then the cert is ok 32 | openssl verify -verbose -CAfile /etc/ssl/certs/DigiCert_Global_Root.pem -untrusted intermediate.pem signer.pem 33 | openssl verify -verbose -CAfile /etc/ssl/certs/Baltimore_CyberTrust_Root.pem -untrusted intermediate.pem signer.pem # This is our old authority. Either is allowed, but Baltimore is deprecated. -------------------------------------------------------------------------------- /IMDSSample.vb: -------------------------------------------------------------------------------- 1 | Imports System.IO 2 | Imports System.Net 3 | Imports Newtonsoft.Json 4 | 5 | Module Module1 6 | 7 | Sub Main() 8 | Dim request As HttpWebRequest = WebRequest.Create("http://169.254.169.254/metadata/instance?api-version=2021-02-01") 9 | ' IMDS requires proxies to be bypassed 10 | Dim proxy As New WebProxy() 11 | request.Headers.Add("Metadata: True") 12 | request.Proxy = proxy 13 | Dim response As HttpWebResponse = request.GetResponse() 14 | Dim dataStream As Stream = response.GetResponseStream() 15 | Dim reader As New StreamReader(dataStream) 16 | Dim responseFromServer As String = reader.ReadToEnd() 17 | 18 | Dim json As String = JsonConvert.SerializeObject(JsonConvert.DeserializeObject(responseFromServer), Formatting.Indented) 19 | Console.WriteLine(json) 20 | reader.Close() 21 | dataStream.Close() 22 | response.Close() 23 | End Sub 24 | 25 | End Module -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright 2016 Microsoft Corporation 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Azure Instance Metadata Samples 2 | 3 | This repo contains samples in various languages to call into Azure Instance Metadata Service from within the VM in Azure. Please refer to LICENSE terms for use. 4 | 5 | More details on Azure Instance Metadata service can be found here https://aka.ms/azureimds 6 | -------------------------------------------------------------------------------- /SECURITY.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | ## Security 4 | 5 | Microsoft takes the security of our software products and services seriously, which includes all source code repositories managed through our GitHub organizations, which include [Microsoft](https://github.com/microsoft), [Azure](https://github.com/Azure), [DotNet](https://github.com/dotnet), [AspNet](https://github.com/aspnet), [Xamarin](https://github.com/xamarin), and [our GitHub organizations](https://opensource.microsoft.com/). 6 | 7 | If you believe you have found a security vulnerability in any Microsoft-owned repository that meets [Microsoft's definition of a security vulnerability](https://aka.ms/opensource/security/definition), please report it to us as described below. 8 | 9 | ## Reporting Security Issues 10 | 11 | **Please do not report security vulnerabilities through public GitHub issues.** 12 | 13 | Instead, please report them to the Microsoft Security Response Center (MSRC) at [https://msrc.microsoft.com/create-report](https://aka.ms/opensource/security/create-report). 14 | 15 | If you prefer to submit without logging in, send email to [secure@microsoft.com](mailto:secure@microsoft.com). If possible, encrypt your message with our PGP key; please download it from the [Microsoft Security Response Center PGP Key page](https://aka.ms/opensource/security/pgpkey). 16 | 17 | You should receive a response within 24 hours. If for some reason you do not, please follow up via email to ensure we received your original message. Additional information can be found at [microsoft.com/msrc](https://aka.ms/opensource/security/msrc). 18 | 19 | Please include the requested information listed below (as much as you can provide) to help us better understand the nature and scope of the possible issue: 20 | 21 | * Type of issue (e.g. buffer overflow, SQL injection, cross-site scripting, etc.) 22 | * Full paths of source file(s) related to the manifestation of the issue 23 | * The location of the affected source code (tag/branch/commit or direct URL) 24 | * Any special configuration required to reproduce the issue 25 | * Step-by-step instructions to reproduce the issue 26 | * Proof-of-concept or exploit code (if possible) 27 | * Impact of the issue, including how an attacker might exploit the issue 28 | 29 | This information will help us triage your report more quickly. 30 | 31 | If you are reporting for a bug bounty, more complete reports can contribute to a higher bounty award. Please visit our [Microsoft Bug Bounty Program](https://aka.ms/opensource/security/bounty) page for more details about our active programs. 32 | 33 | ## Preferred Languages 34 | 35 | We prefer all communications to be in English. 36 | 37 | ## Policy 38 | 39 | Microsoft follows the principle of [Coordinated Vulnerability Disclosure](https://aka.ms/opensource/security/cvd). 40 | 41 | 42 | -------------------------------------------------------------------------------- /imdssample.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "io/ioutil" 6 | "net/http" 7 | ) 8 | 9 | func main() { 10 | var PTransport = & http.Transport { Proxy: nil } 11 | 12 | client := http.Client { Transport: PTransport } 13 | 14 | req, _ := http.NewRequest("GET", "http://169.254.169.254/metadata/instance", nil) 15 | req.Header.Add("Metadata", "True") 16 | 17 | q := req.URL.Query() 18 | q.Add("format", "json") 19 | q.Add("api-version", "2021-02-01") 20 | req.URL.RawQuery = q.Encode() 21 | 22 | resp, err := client.Do(req) 23 | if err != nil { 24 | fmt.Println("Errored when sending request to the server") 25 | return 26 | } 27 | 28 | defer resp.Body.Close() 29 | resp_body, _ := ioutil.ReadAll(resp.Body) 30 | 31 | fmt.Println(resp.Status) 32 | fmt.Println(string(resp_body)) 33 | } 34 | -------------------------------------------------------------------------------- /imdssample.java: -------------------------------------------------------------------------------- 1 | package com.microsoft.azure.imds.samples; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.ByteArrayInputStream; 5 | import java.io.InputStreamReader; 6 | import java.net.HttpURLConnection; 7 | import java.net.URL; 8 | import java.security.cert.CertificateFactory; 9 | import java.security.cert.X509Certificate; 10 | import java.util.Collection; 11 | import java.util.Iterator; 12 | import javax.security.auth.x500.X500Principal; 13 | import org.bouncycastle.cms.CMSSignedData; 14 | import org.bouncycastle.cms.CMSTypedData; 15 | import org.bouncycastle.util.encoders.Base64; 16 | import com.google.gson.Gson; 17 | 18 | /** 19 | * This example has two dependencies: 20 | * 1. Google Gson library: https://github.com/google/gson 21 | * 2. BouncyCastle Java library: https://www.bouncycastle.org/java.html 22 | */ 23 | public class IMDSSample 24 | { 25 | public static final String ImdsServer = "http://169.254.169.254"; 26 | public static final String InstanceEndpoint = ImdsServer + "/metadata/instance"; 27 | public static final String AttestedEndpoint = ImdsServer + "/metadata/attested/document"; 28 | public static final String NonceValue = "123456"; 29 | 30 | public static void main(String[] args) 31 | { 32 | // Query /instance metadata 33 | String result = QueryInstanceEndpoint(); 34 | ParseInstanceResponse(result); 35 | 36 | // Make Attested call and parse the response 37 | result = QueryAttestedEndpoint(); 38 | ParseAttestedResponse(result); 39 | } 40 | 41 | private static void ParseInstanceResponse(String response) 42 | { 43 | System.out.println("Instance response: " + response); 44 | } 45 | 46 | private static void ParseAttestedResponse(String response) 47 | { 48 | System.out.println("Parsing Attested response"); 49 | AttestedDocument document = new Gson().fromJson(response, AttestedDocument.class); 50 | byte[] decoded = Base64.decode(document.signature); 51 | ValidateCertificate(decoded); 52 | ValidateAttestedData(decoded); 53 | } 54 | 55 | private static void ValidateCertificate(byte[] decoded) 56 | { 57 | try 58 | { 59 | CertificateFactory factory = CertificateFactory.getInstance("X.509"); 60 | Collection certs = factory.generateCertificates(new ByteArrayInputStream(decoded)); 61 | Iterator it = certs.iterator(); 62 | while(it.hasNext()) 63 | { 64 | X509Certificate cert = (X509Certificate)it.next(); 65 | cert.checkValidity(); 66 | X500Principal issuer = cert.getIssuerX500Principal(); 67 | System.out.println("Issuer: " + issuer.toString()); 68 | X500Principal subject = cert.getSubjectX500Principal(); 69 | System.out.println("Subject: " + subject.toString()); 70 | System.out.println("Valid until: " + cert.getNotAfter().toString()); 71 | } 72 | } 73 | catch(Exception ex) 74 | { 75 | System.out.println("Exception validating certificate: " + ex.getMessage()); 76 | } 77 | } 78 | 79 | private static void ValidateAttestedData(byte[] decoded) 80 | { 81 | try 82 | { 83 | CMSSignedData signature = new CMSSignedData(decoded); 84 | CMSTypedData signedData = signature.getSignedContent(); 85 | String signedDataString = new String((byte[])signedData.getContent()); 86 | System.out.println("Attested data: " + signedDataString); 87 | AttestedData data = new Gson().fromJson(signedDataString, AttestedData.class); 88 | if(data.nonce.compareTo(NonceValue) == 0) 89 | { 90 | System.out.println("Nonce values match"); 91 | } 92 | // You should also verify the plan and subscription information 93 | } 94 | catch(Exception ex) 95 | { 96 | System.out.println("Exception validating data: " + ex.getMessage()); 97 | } 98 | } 99 | 100 | private static String QueryInstanceEndpoint() 101 | { 102 | return QueryImds(InstanceEndpoint, "2021-02-01"); 103 | } 104 | 105 | private static String QueryAttestedEndpoint() 106 | { 107 | String nonce = "nonce=" + NonceValue; 108 | return QueryImds(AttestedEndpoint, "2021-02-01", nonce); 109 | } 110 | 111 | private static String QueryImds(String path, String apiVersion) 112 | { 113 | return QueryImds(path, apiVersion, ""); 114 | } 115 | 116 | private static String QueryImds(String path, String apiVersion, String otherParams) 117 | { 118 | String imdsUrl = path + "?api-version=" + apiVersion; 119 | if(otherParams != null && !otherParams.isEmpty()) 120 | { 121 | imdsUrl += "&" + otherParams; 122 | } 123 | 124 | try 125 | { 126 | URL url = new URL(imdsUrl); 127 | HttpURLConnection con = (HttpURLConnection) url.openConnection(Proxy.NO_PROXY); 128 | con.setRequestMethod("GET"); 129 | con.setRequestProperty("Metadata", "True"); 130 | BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); 131 | String line; 132 | StringBuffer response = new StringBuffer(); 133 | while ((line = in.readLine()) != null) { 134 | response.append(line); 135 | } 136 | in.close(); 137 | return response.toString(); 138 | } 139 | catch(Exception ex) 140 | { 141 | return ""; 142 | } 143 | } 144 | 145 | public class AttestedDocument 146 | { 147 | public String encoding; 148 | public String signature; 149 | } 150 | 151 | public class AttestedData 152 | { 153 | public String nonce; 154 | public String vmId; 155 | public String subscriptionId; 156 | public AttestedDataPlanInfo plan; 157 | public AttestedDataTimeStamp timeStamp; 158 | } 159 | 160 | public class AttestedDataPlanInfo 161 | { 162 | public String name; 163 | public String product; 164 | public String publisher; 165 | } 166 | 167 | public class AttestedDataTimeStamp 168 | { 169 | public String createdOn; 170 | public String expiresOn; 171 | } 172 | 173 | } 174 | -------------------------------------------------------------------------------- /user-data-arm-template/README.md: -------------------------------------------------------------------------------- 1 | # Introducing User Data 2 | 3 | When creating a new VM, you can specify a set of data to be used during or after the VM provision, and retrieve it through IMDS. 4 | 5 | To set up user data, utilize the quickstart template here. 6 | 7 | **Note:** This feature is released with IMDS version 2021-01-01 and depends upon an update to the Azure platform, which is currently being rolled out and may not yet be available in every region. 8 | 9 | **Note:** Security notice: IMDS is open to all applications on the VM, sensitive data should not be placed in the user data. 10 | 11 | To retirve the user data, utilize the sample code below: 12 | 13 | ### Windows 14 | ```powershell 15 | Invoke-RestMethod -Headers @{"Metadata"="true"} -Method GET -Proxy $Null -Uri "http://169.254.169.254/metadata/instance/compute/userData?api-version=2021-01-01&format=text" | base64 --decode 16 | ``` 17 | 18 | ### Linux 19 | 20 | ```bash 21 | curl -H Metadata:true --noproxy "*" "http://169.254.169.254/metadata/instance/compute/userData?api-version=2021-01-01&format=text" | base64 --decode 22 | ``` 23 | 24 | ## How about custom data? 25 | 26 | User data offers the similar functionality to custom data, allowing you to pass your own metadata to the VM instance. The difference is, user data is retrieved through IMDS, and is persistent throughout the lifetime of the VM instance. Existing custom data feature will continue to work as described in [this article](https://docs.microsoft.com/azure/virtual-machines/custom-data). However you can only get custom data through local system folder, not through IMDS. 27 | 28 | ## Deploy a Virtual Machine with UserData 29 | 30 | This template allows you to create a Virtual Machine with User Data. This template also deploys a Virtual Network, Public IP addresses, and a Network Interface. 31 | -------------------------------------------------------------------------------- /user-data-arm-template/azuredeploy.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#", 3 | "contentVersion": "1.0.0.0", 4 | "parameters": { 5 | "dnsLabelPrefix": { 6 | "type": "string", 7 | "defaultValue": "[uniqueString(resourceGroup().id)]", 8 | "metadata": { 9 | "description": "Unique DNS Name for the public IP address" 10 | } 11 | }, 12 | "adminUsername": { 13 | "type": "string", 14 | "metadata": { 15 | "description": "User name for the Virtual Machine." 16 | } 17 | }, 18 | "userData": { 19 | "type": "string", 20 | "metadata": { 21 | "description": "String passed down to the Virtual Machine." 22 | } 23 | }, 24 | "vmSize": { 25 | "type": "string", 26 | "defaultValue": "Standard_D2_v2", 27 | "metadata": { 28 | "description": "VM size" 29 | } 30 | }, 31 | "ubuntuOSVersion": { 32 | "type": "string", 33 | "defaultValue": "18.04-LTS", 34 | "allowedValues": [ 35 | "12.04.5-LTS", 36 | "14.04.5-LTS", 37 | "16.04.0-LTS", 38 | "18.04-LTS" 39 | ], 40 | "metadata": { 41 | "description": "The Ubuntu version for the VM. This will pick a fully patched image of this given Ubuntu version. Allowed values: 12.04.5-LTS, 14.04.2-LTS, 15.10." 42 | } 43 | }, 44 | "location": { 45 | "type": "string", 46 | "defaultValue": "[resourceGroup().location]", 47 | "metadata": { 48 | "description": "Location for all resources." 49 | } 50 | }, 51 | "authenticationType": { 52 | "type": "string", 53 | "defaultValue": "sshPublicKey", 54 | "allowedValues": [ 55 | "sshPublicKey", 56 | "password" 57 | ], 58 | "metadata": { 59 | "description": "Type of authentication to use on the Virtual Machine. SSH key is recommended." 60 | } 61 | }, 62 | "adminPasswordOrKey": { 63 | "type": "securestring", 64 | "metadata": { 65 | "description": "SSH Key or password for the Virtual Machine. SSH key is recommended." 66 | } 67 | } 68 | }, 69 | "variables": { 70 | "imagePublisher": "Canonical", 71 | "imageOffer": "UbuntuServer", 72 | "nicName": "networkInterface1", 73 | "vmName": "vm1", 74 | "virtualNetworkName": "virtualNetwork1", 75 | "publicIPAddressName": "publicIp1", 76 | "addressPrefix": "10.0.0.0/16", 77 | "subnet1Name": "Subnet-1", 78 | "subnet1Prefix": "10.0.0.0/24", 79 | "publicIPAddressType": "Dynamic", 80 | "linuxConfiguration": { 81 | "disablePasswordAuthentication": true, 82 | "ssh": { 83 | "publicKeys": [ 84 | { 85 | "path": "[concat('/home/', parameters('adminUsername'), '/.ssh/authorized_keys')]", 86 | "keyData": "[parameters('adminPasswordOrKey')]" 87 | } 88 | ] 89 | } 90 | }, 91 | "networkSecurityGroupName": "default-NSG" 92 | }, 93 | "resources": [ 94 | { 95 | "apiVersion": "2019-06-01", 96 | "type": "Microsoft.Network/publicIPAddresses", 97 | "name": "[variables('publicIPAddressName')]", 98 | "location": "[parameters('location')]", 99 | "properties": { 100 | "publicIPAllocationMethod": "[variables('publicIPAddressType')]", 101 | "dnsSettings": { 102 | "domainNameLabel": "[parameters('dnsLabelPrefix')]" 103 | } 104 | } 105 | }, 106 | { 107 | "comments": "Default Network Security Group for template", 108 | "type": "Microsoft.Network/networkSecurityGroups", 109 | "apiVersion": "2019-08-01", 110 | "name": "[variables('networkSecurityGroupName')]", 111 | "location": "[parameters('location')]", 112 | "properties": { 113 | "securityRules": [ 114 | { 115 | "name": "default-allow-22", 116 | "properties": { 117 | "priority": 1000, 118 | "access": "Allow", 119 | "direction": "Inbound", 120 | "destinationPortRange": "22", 121 | "protocol": "Tcp", 122 | "sourceAddressPrefix": "*", 123 | "sourcePortRange": "*", 124 | "destinationAddressPrefix": "*" 125 | } 126 | } 127 | ] 128 | } 129 | }, 130 | { 131 | "apiVersion": "2019-06-01", 132 | "type": "Microsoft.Network/virtualNetworks", 133 | "name": "[variables('virtualNetworkName')]", 134 | "location": "[parameters('location')]", 135 | "dependsOn": [ 136 | "[resourceId('Microsoft.Network/networkSecurityGroups', variables('networkSecurityGroupName'))]" 137 | ], 138 | "properties": { 139 | "addressSpace": { 140 | "addressPrefixes": [ 141 | "[variables('addressPrefix')]" 142 | ] 143 | }, 144 | "subnets": [ 145 | { 146 | "name": "[variables('subnet1Name')]", 147 | "properties": { 148 | "addressPrefix": "[variables('subnet1Prefix')]", 149 | "networkSecurityGroup": { 150 | "id": "[resourceId('Microsoft.Network/networkSecurityGroups', variables('networkSecurityGroupName'))]" 151 | } 152 | } 153 | } 154 | ] 155 | } 156 | }, 157 | { 158 | "apiVersion": "2019-06-01", 159 | "type": "Microsoft.Network/networkInterfaces", 160 | "name": "[variables('nicName')]", 161 | "location": "[parameters('location')]", 162 | "dependsOn": [ 163 | "[variables('publicIPAddressName')]", 164 | "[variables('virtualNetworkName')]" 165 | ], 166 | "properties": { 167 | "ipConfigurations": [ 168 | { 169 | "name": "ipconfig1", 170 | "properties": { 171 | "privateIPAllocationMethod": "Dynamic", 172 | "publicIPAddress": { 173 | "id": "[resourceId('Microsoft.Network/publicIPAddresses',variables('publicIPAddressName'))]" 174 | }, 175 | "subnet": { 176 | "id": "[resourceId('Microsoft.Network/virtualNetworks/subnets/', variables('virtualNetworkName'), variables('subnet1Name'))]" 177 | 178 | } 179 | } 180 | } 181 | ] 182 | } 183 | }, 184 | { 185 | "apiVersion": "2021-03-01", 186 | "type": "Microsoft.Compute/virtualMachines", 187 | "name": "[variables('vmName')]", 188 | "location": "[parameters('location')]", 189 | "dependsOn": [ 190 | "[variables('nicName')]" 191 | ], 192 | "properties": { 193 | "hardwareProfile": { 194 | "vmSize": "[parameters('vmSize')]" 195 | }, 196 | "osProfile": { 197 | "computerName": "[variables('vmName')]", 198 | "adminUsername": "[parameters('adminUsername')]", 199 | "adminPassword": "[parameters('adminPasswordOrKey')]", 200 | "linuxConfiguration": "[if(equals(parameters('authenticationType'), 'password'), json('null'), variables('linuxConfiguration'))]" 201 | }, 202 | "userData": "[base64(parameters('userData'))]", 203 | "storageProfile": { 204 | "imageReference": { 205 | "publisher": "[variables('imagePublisher')]", 206 | "offer": "[variables('imageOffer')]", 207 | "sku": "[parameters('ubuntuOSVersion')]", 208 | "version": "latest" 209 | }, 210 | "osDisk": { 211 | "createOption": "FromImage" 212 | } 213 | }, 214 | "networkProfile": { 215 | "networkInterfaces": [ 216 | { 217 | "id": "[resourceId('Microsoft.Network/networkInterfaces',variables('nicName'))]" 218 | } 219 | ] 220 | } 221 | } 222 | } 223 | ] 224 | } -------------------------------------------------------------------------------- /user-data-arm-template/azuredeploy.parameters.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentParameters.json#", 3 | "contentVersion": "1.0.0.0", 4 | "parameters": { 5 | "adminUsername": { 6 | "value": "GEN-UNIQUE" 7 | }, 8 | "userData": { 9 | "value": "echo userData" 10 | }, 11 | "dnsLabelPrefix": { 12 | "value": "GEN-UNIQUE" 13 | }, 14 | "adminPasswordOrKey": { 15 | "value": "GEN-SSH-PUB-KEY" 16 | }, 17 | "location": { 18 | "value": "northcentralus" 19 | } 20 | } 21 | } --------------------------------------------------------------------------------