|
17 | 17 | using Microsoft.Extensions.Logging; |
18 | 18 | using Newtonsoft.Json; |
19 | 19 | using RestSharp; |
20 | | -using RestSharp.Authenticators; |
21 | 20 |
|
22 | 21 | using Keyfactor.Logging; |
23 | 22 | using Keyfactor.Orchestrators.Extensions; |
24 | | -using Keyfactor.Extensions.Orchestrator.AxisIPCamera.Model; |
25 | 23 | using Keyfactor.Orchestrators.Extensions.Interfaces; |
| 24 | +using Keyfactor.Extensions.Orchestrator.AxisIPCamera.Exceptions; |
| 25 | +using Keyfactor.Extensions.Orchestrator.AxisIPCamera.Model; |
26 | 26 | using Keyfactor.Extensions.Orchestrator.AxisIPCamera.Helpers; |
27 | 27 |
|
28 | 28 | /* AxisHttpClient.cs |
@@ -67,64 +67,118 @@ public AxisHttpClient(JobConfiguration config, CertificateStore store, IPAMSecre |
67 | 67 | try |
68 | 68 | { |
69 | 69 | var errorContext = new CertificateErrorContext(); |
70 | | - |
| 70 | + |
71 | 71 | Logger = LogHandler.GetClassLogger<AxisHttpClient>(); |
72 | 72 | Logger.LogTrace("Entered AxisHttpClient constructor."); |
73 | 73 | Logger.LogTrace("Initializing Axis IP Camera HTTP client"); |
74 | | - |
| 74 | + |
75 | 75 | // ** NOTE: Ignoring the default config.UseSSL custom field --- we will always connect to the device via HTTPS |
76 | 76 | var baseRestClientUrl = $"https://{store.ClientMachine}"; |
77 | | - |
| 77 | + |
78 | 78 | Logger.LogDebug($"Base HTTP client URL: {baseRestClientUrl}"); |
79 | 79 |
|
80 | | - // Initialize custom HTTP handler to validate device identity |
81 | | - RestClientOptions options = null; |
82 | | - Logger.LogTrace($"Adding custom TLS cert validator to the HTTP client options..."); |
| 80 | + // Retrieve username and password credentials to connect to the device |
| 81 | + Logger.LogTrace("Adding device credentials to the HTTP client options..."); |
| 82 | + string username = PAMUtilities.ResolvePAMField(resolver, Logger, "API Username", config.ServerUsername); |
| 83 | + string password = PAMUtilities.ResolvePAMField(resolver, Logger, "API Password", config.ServerPassword); |
| 84 | + |
| 85 | + // See ADR-0001 Axis Camera Authentication Negotiation |
| 86 | + // https://keyfactor.atlassian.net/wiki/spaces/IoTStrategy/pages/2968584197/ADR-0001+Axis+Camera+Authentication+Negotiation |
| 87 | + // |
| 88 | + // The client intentionally uses HttpClientHandler credentials |
| 89 | + // rather than RestSharp's HttpBasicAuthenticator to allow |
| 90 | + // automatic negotiation of Basic vs Digest authentication |
| 91 | + // based on the authentication challenge presented by the camera. |
| 92 | + Logger.LogInformation($"Adding custom TLS cert validator to the HTTP client options."); |
| 93 | + Logger.LogInformation($"Using HttpClientHandler credential negotiation for camera authentication."); |
83 | 94 | var handler = new HttpClientHandler |
84 | 95 | { |
85 | 96 | ServerCertificateCustomValidationCallback = |
86 | | - DeviceCertValidator.GetValidator(store.StorePath, errorContext, Logger) |
| 97 | + DeviceCertValidator.GetValidator( |
| 98 | + store.StorePath, |
| 99 | + errorContext, |
| 100 | + Logger), |
| 101 | + |
| 102 | + Credentials = new NetworkCredential(username, password), |
| 103 | + |
| 104 | + PreAuthenticate = |
| 105 | + false // PreAuthenticate is set to false to avoid the default behavior of sending the username and password in the Authorization header |
87 | 106 | }; |
| 107 | + // End ADR-0001 |
88 | 108 |
|
89 | 109 | // Initialize HTTP client options with the base URL and custom TLS cert validator |
90 | | - options = new RestClientOptions(baseRestClientUrl) |
| 110 | + RestClientOptions options = new RestClientOptions(baseRestClientUrl) |
91 | 111 | { |
92 | 112 | ConfigureMessageHandler = _ => handler |
93 | 113 | }; |
94 | 114 |
|
95 | | - // Add Basic Auth username and password credentials |
96 | | - Logger.LogTrace("Adding Basic Auth Credentials to the HTTP client options..."); |
97 | | - string username = PAMUtilities.ResolvePAMField(resolver, Logger, "API Username", config.ServerUsername); |
98 | | - string password = PAMUtilities.ResolvePAMField(resolver, Logger, "API Password", config.ServerPassword); |
99 | | - |
100 | | - options.Authenticator = new HttpBasicAuthenticator(username, password); |
101 | | - |
102 | 115 | // Add SSL validation |
103 | 116 | Logger.LogTrace("Validating connection to the device..."); |
104 | 117 |
|
105 | 118 | _httpClient = new RestClient(options); |
106 | | - var request = new RestRequest("/"); // Initiates the TLS handshake to retrieve the server cert |
| 119 | + // Initiates the TLS handshake to verify the ability to authenticate to the camera |
| 120 | + var request = new RestRequest("axis-cgi/param.cgi?action=list&group=Network.HTTP.AuthenticationPolicy"); |
107 | 121 | var response = _httpClient.Execute(request); |
108 | 122 |
|
109 | | - // Build the list of errors to log to the console |
| 123 | + Logger.LogTrace($"Connection to the device response status code: {response.StatusCode}"); |
| 124 | + |
| 125 | + // Build the list of SSL certificate errors and log to the console |
110 | 126 | StringBuilder errorSb = new StringBuilder(); |
111 | 127 | if (errorContext.HasErrors) |
112 | 128 | { |
113 | 129 | foreach (var error in errorContext.Errors) |
114 | 130 | { |
115 | 131 | errorSb.AppendLine(error); |
116 | 132 | } |
117 | | - throw new Exception(errorSb.ToString()); |
| 133 | + |
| 134 | + throw new DeviceCertValidationException( |
| 135 | + $"Device TLS cert validator errors encountered --- {errorSb}"); |
| 136 | + } |
| 137 | + |
| 138 | + // Begin ADR-0001 Axis Camera Authentication Negotiation |
| 139 | + // Log the WWW-Authenticate headers if 401 Unauthorized returned |
| 140 | + // Throw exception if connection cannot be made successfully to the camera |
| 141 | + if (response.StatusCode == HttpStatusCode.Unauthorized) |
| 142 | + { |
| 143 | + Logger.LogWarning("Camera returned 401 Unauthorized"); |
| 144 | + |
| 145 | + foreach (var header in response.Headers) |
| 146 | + { |
| 147 | + Logger.LogDebug($"WWW-Authenticate header: {header.Value}"); |
| 148 | + } |
| 149 | + |
| 150 | + throw new AuthenticationException( |
| 151 | + "Authentication to the Axis camera failed due to 401 Unauthorized. Verify the configured credentials."); |
118 | 152 | } |
119 | | - |
120 | | - Logger.LogTrace($"Connection to the device response status code: {response.StatusCode}"); |
| 153 | + |
| 154 | + if (!response.IsSuccessful) |
| 155 | + { |
| 156 | + throw new Exception(response.ErrorMessage); |
| 157 | + } |
| 158 | + // End ADR-0001 |
| 159 | + |
121 | 160 | Logger.LogTrace("Completed Initialization of Axis IP Camera HTTP Client"); |
122 | 161 | Logger.LogTrace("Leaving AxisHttpClient constructor."); |
123 | 162 | } |
124 | | - catch (Exception e) |
| 163 | + catch (DeviceCertValidationException ex) |
| 164 | + { |
| 165 | + Logger.LogError("Device TLS cert validation failed while connecting to the device: " + LogHandler.FlattenException(ex)); |
| 166 | + throw new Exception(ex.Message); |
| 167 | + } |
| 168 | + catch (AuthenticationException ex1) |
| 169 | + { |
| 170 | + Logger.LogError("Authentication to the device failed: " + LogHandler.FlattenException(ex1)); |
| 171 | + throw new Exception(ex1.Message); |
| 172 | + } |
| 173 | + catch (HttpRequestException ex2) |
| 174 | + { |
| 175 | + Logger.LogError("Failed to communicate with the device: " + LogHandler.FlattenException(ex2)); |
| 176 | + throw new Exception(ex2.Message); |
| 177 | + } |
| 178 | + catch (Exception ex3) |
125 | 179 | { |
126 | | - Logger.LogError("Error initializing Axis IP Camera HTTP Client: " + LogHandler.FlattenException(e)); |
127 | | - throw new Exception($"Device identity could not be verified successfully --- {e.Message}"); |
| 180 | + Logger.LogError("Unexpected error while connecting to the device: " + LogHandler.FlattenException(ex3)); |
| 181 | + throw new Exception(ex3.Message); |
128 | 182 | } |
129 | 183 | } |
130 | 184 |
|
|
0 commit comments