Пример #1
0
        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));
        }
Пример #2
0
        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);
            }
        }
Пример #3
0
        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();
        }
Пример #4
0
        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);
        }
Пример #5
0
        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);
        }
Пример #6
0
        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);
        }