public DtoSocketServerVerify VerifyServer() { var computerGuid = Context.Headers["computerGuid"]; var computer = new ServiceComputer().GetByGuid(computerGuid); if (computer == null) { return(null); } var deviceCertEntity = new ServiceCertificate().GetCertificate(computer.CertificateId); var deviceCert = new X509Certificate2(deviceCertEntity.PfxBlob, new EncryptionServices().DecryptText(deviceCertEntity.Password), X509KeyStorageFlags.Exportable); //Calculate UNIX time DateTime epochStart = new DateTime(1970, 01, 01, 0, 0, 0, 0, DateTimeKind.Utc); TimeSpan timeSpan = DateTime.UtcNow - epochStart; string requestTimeStamp = Convert.ToUInt64(timeSpan.TotalSeconds).ToString(); string nonce = Guid.NewGuid().ToString("N"); string signatureRawData = requestTimeStamp + nonce; var csp = (RSACryptoServiceProvider)deviceCert.PrivateKey; SHA1Managed sha1 = new SHA1Managed(); UnicodeEncoding encoding = new UnicodeEncoding(); byte[] data = encoding.GetBytes(signatureRawData); byte[] hash = sha1.ComputeHash(data); var signature = csp.SignHash(hash, CryptoConfig.MapNameToOID("SHA1")); var serverVerification = new DtoSocketServerVerify(); serverVerification.nOnce = nonce; serverVerification.Timestamp = requestTimeStamp; serverVerification.signature = Convert.ToBase64String(signature); return(serverVerification); }
public void ServiceCertificate_DefaultCtor() { var cert = new ServiceCertificate(); cert.Status.Should().Be(CertificateStatus.Current); cert.Use.Should().Be(CertificateUse.Both); cert.MetadataPublishOverride.Should().Be(MetadataPublishOverrideType.None); }
public TClass ExecuteSymKeyEncryption <TClass>(RestRequest request, string body) where TClass : new() { request.AddHeader("client", DtoGobalSettings.ClientIdentity.Name); request.AddHeader("identifier", DtoGobalSettings.ClientIdentity.Guid); var serviceSetting = new ServiceSetting(); var entropy = serviceSetting.GetSetting("entropy"); var encryptedKey = serviceSetting.GetSetting("encryption_key"); var decryptedKey = ServiceDP.DecryptData(Convert.FromBase64String(encryptedKey.Value), true, Convert.FromBase64String(entropy.Value)); if (!string.IsNullOrEmpty(body)) { var encryptedContent = new ServiceSymmetricEncryption().EncryptData(decryptedKey, body); request.AddParameter("text/xml", encryptedContent, ParameterType.RequestBody); } var deviceThumbprint = new ServiceSetting().GetSetting("device_thumbprint"); var deviceCert = ServiceCertificate.GetCertificateFromStore(deviceThumbprint.Value, StoreName.My); if (deviceCert == null) { return(default(TClass)); } var encryptedCert = new ServiceSymmetricEncryption().EncryptData(decryptedKey, Convert.ToBase64String(deviceCert.RawData)); request.AddHeader("device_cert", Convert.ToBase64String(encryptedCert)); return(SubmitRequest <TClass>(request, decryptedKey)); }
public override bool AuthorizeHubConnection(HubDescriptor hubDescriptor, IRequest request) { var computerGuid = request.Headers["computerGuid"]; var comServer = request.Headers["comServer"]; var certBase64 = request.Headers["certificate"]; byte[] bytes = Convert.FromBase64String(certBase64); X509Certificate2 x509certificate = new X509Certificate2(bytes); var computer = new ServiceComputer().GetByGuid(computerGuid); if (computer == null) { return(false); } if (!new ServiceCertificate().ValidateCert(x509certificate)) { return(false); } var deviceCertEntity = new ServiceCertificate().GetCertificate(computer.CertificateId); var deviceCert = new X509Certificate2(deviceCertEntity.PfxBlob, new EncryptionServices().DecryptText(deviceCertEntity.Password), X509KeyStorageFlags.Exportable); if (!deviceCert.Equals(x509certificate)) { return(false); } return(true); }
/// <summary> /// Given a thumbprint and password will search the local stores to find a certificate and associated private key /// </summary> IHostedServiceActivity IServiceCertificate.UploadExistingServiceCertificate(string thumbprint, string password) { ServiceCertificate = new ServiceCertificate(string.Empty); ServiceCertificate.GetExisting(thumbprint, password); return(this); }
public void ServiceCertificate_DefaultCtor() { var cert = new ServiceCertificate(); cert.Status.Should().Be(CertificateStatus.Current); cert.Use.Should().Be(CertificateUse.Both); cert.MetadataPublishOverride.Should().Be(MetadataPublishOverrideType.None); }
public UserNamePasswordValidatorBehavior(UserNamePasswordValidator validator) : base() { _validator = validator; UserNameAuthentication.CustomUserNamePasswordValidator = _validator; UserNameAuthentication.UserNamePasswordValidationMode = UserNamePasswordValidationMode.Custom; ServiceCertificate.SetCertificate(StoreLocation.LocalMachine, StoreName.My, X509FindType.FindBySubjectName, "localhost"); }
internal void MakeReadOnly() { _isReadOnly = true; ClientCertificate.MakeReadOnly(); IssuedTokenAuthentication.MakeReadOnly(); SecureConversationAuthentication.MakeReadOnly(); ServiceCertificate.MakeReadOnly(); UserNameAuthentication.MakeReadOnly(); WindowsAuthentication.MakeReadOnly(); }
public CloudServiceTests() { CloudService = new CloudService("Test-" + Guid.NewGuid().ToString("N"), CloudServiceTests.TestLocation); CloudService.Description = "Test Description"; Debug.WriteLine("CloudServiceTests ctor - creating test service"); TestConstants.Subscription.CreateCloudServiceAsync(CloudService).Wait(); var cert = new X509Certificate2(@"..\..\CertKey.pfx", "1234", X509KeyStorageFlags.Exportable); var serviceCertificate = new ServiceCertificate(cert); CloudService.AddServiceCertificateAsync(serviceCertificate).Wait(); }
public bool DownloadFile(RestRequest request, string body, string destination) { if (string.IsNullOrEmpty(body)) { throw new ArgumentException("body"); } request.AddHeader("client", DtoGobalSettings.ClientIdentity.Name); request.AddHeader("identifier", DtoGobalSettings.ClientIdentity.Guid); var serviceSetting = new ServiceSetting(); var entropy = serviceSetting.GetSetting("entropy"); var encryptedKey = serviceSetting.GetSetting("encryption_key"); var decryptedKey = ServiceDP.DecryptData(Convert.FromBase64String(encryptedKey.Value), true, Convert.FromBase64String(entropy.Value)); var encryptedContent = new ServiceSymmetricEncryption().EncryptData(decryptedKey, body); request.AddParameter("text/xml", encryptedContent, ParameterType.RequestBody); var deviceThumbprint = new ServiceSetting().GetSetting("device_thumbprint"); var deviceCert = ServiceCertificate.GetCertificateFromStore(deviceThumbprint.Value, StoreName.My); if (deviceCert == null) { return(false); } var encryptedCert = new ServiceSymmetricEncryption().EncryptData(decryptedKey, Convert.ToBase64String(deviceCert.RawData)); request.AddHeader("device_cert", Convert.ToBase64String(encryptedCert)); try { _log.Debug(request.Resource); using (var stream = File.Create(destination, 4096)) { request.ResponseWriter = (responseStream) => responseStream.CopyTo(stream); _client.DownloadData(request); if (stream.Length == 0) { //something went wrong, rest sharp can't display any other info with downloaddata, so we don't know why return(false); } } return(true); } catch (Exception ex) { _log.Error("Could Not Save File: " + destination); _log.Error(ex.Message); return(false); } }
private void StartWebSocket() { var deviceThumbprint = new ServiceSetting().GetSetting("device_thumbprint"); var deviceCert = ServiceCertificate.GetCertificateFromStore(deviceThumbprint.Value, StoreName.My); if (deviceCert == null) { Logger.Error("Could Not Find The Device Certificate For Web Socket Connection."); Logger.Info("Server Push Events Will Not Be Available"); return; } if (DtoGobalSettings.ComServer == null || DtoGobalSettings.ClientIdentity == null) { Logger.Info("Cannot Connect To Web Socket. The Com Server Has Not Yet Been Set."); Logger.Info("Server Push Events Will Not Be Available"); return; } _hubConnection = new HubConnection(DtoGobalSettings.ComServer); _hubConnection.Headers.Add("certificate", Convert.ToBase64String(deviceCert.GetRawCertData())); _hubConnection.Headers.Add("computerGuid", DtoGobalSettings.ClientIdentity.Guid); _hubConnection.Headers.Add("comServer", DtoGobalSettings.ComServer); var hubProxy = _hubConnection.CreateHubProxy("ActionHub"); _hubConnection.Error += HubConnection_Error; _hubConnection.Start().ContinueWith(task => { if (task.IsFaulted) { Logger.Info("Could Not Connect To Web Socket"); Logger.Error(task.Exception.GetBaseException()); Logger.Info("Server Push Events Will Not Be Available"); return; } else { Logger.Debug("Web Socket Connected. Connection ID: " + _hubConnection.ConnectionId); var v = hubProxy.Invoke <DtoSocketServerVerify>("VerifyServer").Result; if (isValidRequest(v)) { hubProxy.On <DtoHubAction>("ClientAction", hubAction => new ServiceHubAction().Process(hubAction)); } else { Logger.Debug("Socket Server Verification Failed. Disconnecting."); _hubConnection.Stop(); } } }).Wait(); }
public HttpResponseMessage ExportCert(int id) { var cert = new ServiceCertificate().GetCertRawPublic(id); var dataStream = new MemoryStream(cert); var result = new HttpResponseMessage(HttpStatusCode.OK); result.Content = new StreamContent(dataStream); result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment"); result.Content.Headers.ContentDisposition.FileName = "Certificate.cer"; result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); result.Content.Headers.ContentLength = dataStream.Length; return(result); }
/// <summary> /// Creates a service certificate and adds to the remote config /// </summary> public ServiceCertificate CreateServiceCertificateAndAddRemoteDesktop(string username, string password, ref CscfgFile file) { var certificate = new ServiceCertificate(username, password); certificate.Create(); var desktop = new RemoteDesktop(certificate) { Username = username, Password = password }; file.NewVersion = ((ICloudConfig)desktop).ChangeConfig(file.NewVersion); return(certificate); }
public DtoProvisionResponse GetIntermediateCert() { var rawCert = new ServiceCertificate().GetIntermediatePublic(); var response = new DtoProvisionResponse(); if (rawCert != null) { response.Certificate = Convert.ToBase64String(rawCert); response.ProvisionStatus = EnumProvisionStatus.Status.IntermediateInstalled; } else { response.Certificate = null; response.ProvisionStatus = EnumProvisionStatus.Status.Error; response.Message = "Could Not Locate Intermediate Certificate On Server."; } return(response); }
private byte[] GenerateDeviceCert(string symmKey, EntityComputer computer) { var iCert = new ServiceCertificate().GetIntermediate(); byte[] symmetricKey; using (RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)iCert.PrivateKey) { var encryptedKey = Convert.FromBase64String(symmKey); symmetricKey = rsa.Decrypt(encryptedKey, true); } var intermediateEntity = new ServiceCertificate().GetIntermediateEntity(); var pass = new EncryptionServices().DecryptText(intermediateEntity.Password); var intermediateCert = new X509Certificate2(intermediateEntity.PfxBlob, pass, X509KeyStorageFlags.Exportable); var certRequest = new CertificateRequest(); var organization = ServiceSetting.GetSettingValue(SettingStrings.CertificateOrganization); certRequest.SubjectName = string.Format("O={0},CN={1}", organization, computer.Guid); certRequest.NotBefore = DateTime.UtcNow; certRequest.NotAfter = certRequest.NotBefore.AddYears(10); var certificate = new ServiceGenerateCertificate(certRequest).IssueCertificate(intermediateCert, false, false); var c = new EntityCertificate(); c.NotAfter = certificate.NotAfter; c.NotBefore = certificate.NotBefore; c.Serial = certificate.SerialNumber; var pfxPass = Membership.GeneratePassword(10, 0); c.Password = new EncryptionServices().EncryptText(pfxPass); c.PfxBlob = certificate.Export(X509ContentType.Pfx, pfxPass); c.SubjectName = certificate.Subject; c.Type = EnumCertificate.CertificateType.Device; var base64DeviceCert = Convert.ToBase64String(certificate.RawData); var encryptedCert = new ServiceSymmetricEncryption().EncryptData(symmetricKey, base64DeviceCert); new ServiceCertificate().AddCertificate(c); computer.CertificateId = c.Id; computer.ProvisionStatus = EnumProvisionStatus.Status.PendingConfirmation; computer.SymmKeyEncrypted = new EncryptionServices().EncryptText(Convert.ToBase64String(symmetricKey)); return(encryptedCert); }
public StringContent ResponseHandler(Task <HttpResponseMessage> task, byte[] key, EntityComputer computer) { //encrypt the response back to the client //var headers = task.Result.ToString(); if (task.Result.Content != null) { Logger.Debug($"ID: {logId} - Encrypting response body"); var body = task.Result.Content.ReadAsStringAsync().Result; Logger.Debug($"ID: {logId} - {body}"); var encryptedContent = new ServiceSymmetricEncryption().EncryptData(key, body); var signature = new ServiceCertificate().SignMessage(Convert.ToBase64String(encryptedContent), computer); var jsonResp = new DtoApiStringResponse(); jsonResp.Value = Convert.ToBase64String(encryptedContent); task.Result.Headers.Add("client_signature", Convert.ToBase64String(signature)); return(new StringContent(JsonConvert.SerializeObject(jsonResp), Encoding.UTF8, "application/json")); } else { return(null); } }
private async Task <bool> isValidRequest(HttpRequestMessage req, string incomingBase64Signature, string nonce, string requestTimeStamp) { var requestContentBase64String = ""; var requestUri = HttpUtility.UrlEncode(req.RequestUri.AbsoluteUri.ToLower()); var requestHttpMethod = req.Method.Method; if (isReplayRequest(nonce, requestTimeStamp)) { Logger.Debug($"ID: {logId} - Request appears to be a replay, denying {nonce} {requestTimeStamp}"); return(false); } var hash = await ComputeHash(req.Content); if (hash != null) { requestContentBase64String = Convert.ToBase64String(hash); } var data = string.Format("{0}{1}{2}{3}{4}", requestHttpMethod, requestUri, requestTimeStamp, nonce, requestContentBase64String); Logger.Debug($"ID: {logId} - Expected Signature Data " + data); var deviceThumbprint = new ServiceSetting().GetSetting("device_thumbprint"); var deviceCert = ServiceCertificate.GetCertificateFromStore(deviceThumbprint.Value, StoreName.My); if (deviceCert == null) { Logger.Error("Could Not Find The Device Certificate For Signature Verification."); return(false); } if (!ServiceCertificate.VerifySignature(deviceCert, Convert.FromBase64String(incomingBase64Signature), data)) { return(false); } return(true); }
/// <summary> /// Generates a service certificate and adds the appropriate text to the <certificates/> tag in the .cscfg file /// </summary> IHostedServiceActivity IServiceCertificate.GenerateAndAddServiceCertificate(string name) { ServiceCertificate = new ServiceCertificate(name); // we have to also create the certificate! ServiceCertificate.Create(); // add these to the config list we have to implement changes to if (EnableSsl) { CloudConfigChanges.Add(new SslEnablement(ServiceCertificate, SslRoleName)); } if (EnableRemoteDesktop) { CloudConfigChanges.Add(new RemoteDesktop(ServiceCertificate, RdRoleName) { Username = RdUsername, Password = RdPassword }); } return(this); }
private bool isValidRequest(DtoSocketServerVerify verification) { if (isReplayRequest(verification.nOnce, verification.Timestamp)) { Logger.Debug($"ID: {_logId} - Request appears to be a replay, denying {verification.nOnce} {verification.Timestamp}"); return(false); } var deviceThumbprint = new ServiceSetting().GetSetting("device_thumbprint"); var deviceCert = ServiceCertificate.GetCertificateFromStore(deviceThumbprint.Value, StoreName.My); if (deviceCert == null) { Logger.Error("Could Not Find The Device Certificate For Signature Verification."); return(false); } if (!ServiceCertificate.VerifySignature(deviceCert, Convert.FromBase64String(verification.signature), verification.Timestamp + verification.nOnce)) { return(false); } return(true); }
private async Task <bool> isValidRequest(string computerGuid, string deviceCert) { var computerEntity = new ServiceComputer().GetByGuid(computerGuid); if (computerEntity == null) { Logger.Debug($"ID: {logId} - Computer with identifier {computerGuid} was not found"); return(false); } var computerCert = new ServiceCertificate().GetCertX509Public(computerEntity.CertificateId); if (computerCert == null) { Logger.Debug($"ID: {logId} - Computer device certificate was null"); return(false); } var authorizationCert = new X509Certificate2(Convert.FromBase64String(deviceCert)); if (!computerCert.Equals(authorizationCert)) { Logger.Debug($"ID: {logId} - Certificate mismatch b/w what was sent and current device certificate"); return(false); } if (new ServiceCertificate().ValidateCert(authorizationCert)) { return(true); } else { Logger.Debug($"ID: {logId} - Certificate failed validation"); return(false); } }
private TClass SubmitRequest <TClass>(RestRequest request, byte[] encKey = null) where TClass : new() { if (request == null) { _log.Error("Could Not Execute API Request. The Request was empty." + new TClass().GetType()); return(default(TClass)); } _log.Debug(request.Resource); var response = _client.Execute <TClass>(request); if (response == null) { _log.Error("Could Not Complete API Request. The Response was empty." + request.Resource); return(default(TClass)); } if (response.StatusCode == HttpStatusCode.InternalServerError) { _log.Error("Could Not Complete API Request. The Response Produced An Error." + request.Resource); _log.Error(response.Content); try { if (encKey != null) { var encryptedresponse = JsonConvert.DeserializeObject <DtoStringResponse>(response.Content); var content = new ServiceSymmetricEncryption().Decrypt(encKey, Convert.FromBase64String(encryptedresponse.Value)); _log.Error(content); } } catch { //ignore } return(default(TClass)); } if (response.StatusCode == HttpStatusCode.Unauthorized) { _log.Error("The Request Was Unauthorized " + request.Resource); return(default(TClass)); } if (response.StatusCode == HttpStatusCode.NotFound) { _log.Error("Error Retrieving API Response: Not Found " + request.Resource); return(default(TClass)); } if (response.ErrorException != null && encKey == null) { _log.Error("Error Retrieving API Response: " + response.ErrorException); return(default(TClass)); } if (response.Data == null && encKey == null) { _log.Error("Response Data Was Null For Resource: " + request.Resource); return(default(TClass)); } if (encKey != null) { if (response.Headers.Any(t => t.Name.Equals("client_signature"))) { var firstOrDefault = response.Headers.FirstOrDefault(t => t.Name.Equals("client_signature")); if (firstOrDefault == null) { _log.Error("The Response Signature Is Not Valid For This Device: " + request.Resource); return(default(TClass)); } var deviceThumbprint = new ServiceSetting().GetSetting("device_thumbprint"); var deviceCert = ServiceCertificate.GetCertificateFromStore(deviceThumbprint.Value, StoreName.My); if (deviceCert == null) { _log.Error("Could Not Find The Device Certificate: " + request.Resource); return(default(TClass)); } var signature = firstOrDefault.Value.ToString(); var encryptedresponse = JsonConvert.DeserializeObject <DtoStringResponse>(response.Content); if ( !ServiceCertificate.VerifySignature(deviceCert, Convert.FromBase64String(signature), encryptedresponse.Value)) { _log.Error("Response Signature Verification Failed: " + request.Resource); return(default(TClass)); } var content = new ServiceSymmetricEncryption().Decrypt(encKey, Convert.FromBase64String(encryptedresponse.Value)); return(JsonConvert.DeserializeObject <TClass>(content)); } _log.Error("Invalid Reponse, Signature Missing: " + request.Resource); return(default(TClass)); } return(response.Data); }
private void ResetToec() { if (!_imagePrepOptions.ResetToec) { return; } AppendLogText("Resetting Toec"); ServiceCertificate.DeleteAllDeviceCertificates(); ServiceCertificate.DeleteIntermediate(); var serviceSetting = new ServiceSetting(); var installationId = serviceSetting.GetSetting("installation_id"); installationId.Value = null; serviceSetting.UpdateSettingValue(installationId); var encryptionKey = serviceSetting.GetSetting("encryption_key"); encryptionKey.Value = null; serviceSetting.UpdateSettingValue(encryptionKey); var entropy = serviceSetting.GetSetting("entropy"); entropy.Value = null; serviceSetting.UpdateSettingValue(entropy); var computerIdentifier = serviceSetting.GetSetting("computer_identifier"); computerIdentifier.Value = null; serviceSetting.UpdateSettingValue(computerIdentifier); var deviceThumbprint = serviceSetting.GetSetting("device_thumbprint"); deviceThumbprint.Value = null; serviceSetting.UpdateSettingValue(deviceThumbprint); var intermediateThumbprint = serviceSetting.GetSetting("intermediate_thumbprint"); intermediateThumbprint.Value = null; serviceSetting.UpdateSettingValue(intermediateThumbprint); new PolicyHistoryServices().DeleteAll(); new ServiceUserTracker().DeleteAll(); new ServiceAppMonitor().DeleteAll(); var provisionStatus = serviceSetting.GetSetting("provision_status"); provisionStatus.Value = "0"; serviceSetting.UpdateSettingValue(provisionStatus); var updatedStatus = serviceSetting.GetSetting("provision_status"); var updatedId = installationId = serviceSetting.GetSetting("installation_id"); if (!updatedStatus.Value.Equals("0") && !string.IsNullOrEmpty(updatedId.Value)) { AppendLogText("Prepare Image Failed. Could Not Reset ID's"); } AppendLogText("Finished Resetting Toec"); }
public byte[] UpdateMsis(bool is64bit) { var expectedClient = new ServiceVersion().Get(1).LatestClientVersion; if (string.IsNullOrEmpty(expectedClient)) { Logger.Error("Cannot Create MSI. Unknown Expected Toec Version"); return(null); } var type = is64bit ? "-x64.msi" : "-x86.msi"; var basePath = Path.Combine(HttpContext.Current.Server.MapPath("~"), "private", "agent"); var stockFileFullPath = Path.Combine(basePath, $"Toec-{expectedClient}{type}"); if (!File.Exists(stockFileFullPath)) { Logger.Debug("Cannot Create MSI. Could Not Locate Stock MSI"); return(null); } var ca = new ServiceCertificate().GetCAPublic(); if (ca == null) { Logger.Debug("Cannot Create MSI. Certificate Chain Must First Be Created. "); return(null); } var newVersion = expectedClient.Split('.'); var v = string.Join(".", newVersion.Take(newVersion.Length - 1)); var outputFileName = $"Toec-{v}{type}"; var outputFileFullPath = Path.Combine(basePath, outputFileName); try { File.Delete(outputFileFullPath); } catch { //ignored } try { File.Copy(stockFileFullPath, outputFileFullPath); } catch (Exception ex) { Logger.Error("Could Not Create MSI."); Logger.Error(ex.Message); return(null); } Stream stream = new MemoryStream(ca); Database database = null; View serverKey = null; View thumbprint = null; View comServers = null; View cert = null; Record rec = null; GetMsiArgs(); using (database = new Database(outputFileFullPath, DatabaseOpenMode.Transact)) { try { serverKey = database.OpenView(String.Format("INSERT INTO Property (Property, Value) VALUES ('{0}', '{1}')", "SERVER_KEY", _serverKey)); serverKey.Execute(); serverKey.Close(); comServers = database.OpenView(String.Format("INSERT INTO Property (Property, Value) VALUES ('{0}', '{1}')", "COM_SERVERS", _comServers)); comServers.Execute(); comServers.Close(); thumbprint = database.OpenView(String.Format("INSERT INTO Property (Property, Value) VALUES ('{0}', '{1}')", "CA_THUMBPRINT", _thumbprint)); thumbprint.Execute(); thumbprint.Close(); cert = database.OpenView("UPDATE `Binary` SET `Data` = ? WHERE `Name` = 'ToemsCA.Binary'"); rec = new Record(1); rec.SetStream(1, stream); cert.Execute(rec); cert.Close(); database.Commit(); } catch (Exception ex) { Logger.Error("Could Not Create Msi."); Logger.Error(ex.Message); return(null); } finally { if (rec != null) { rec.Close(); } if (serverKey != null) { serverKey.Close(); } if (thumbprint != null) { thumbprint.Close(); } if (comServers != null) { comServers.Close(); } if (cert != null) { cert.Close(); } if (database != null) { database.Close(); } } } var file = File.ReadAllBytes(outputFileFullPath); return(file); }