/// <summary> /// Creates HTTP Request for well defined remote host /// </summary> private byte[] CreateRequest(DnsInfo dns) { using (SHA1 sha1 = SHA1.Create()) { byte[] hash = sha1.ComputeHash(Guid.NewGuid().ToByteArray()); WebSocketKey = Convert.ToBase64String(hash); } string request = HttpHeaders.HTTP_GET + " " + dns.Path + " " + HttpHeaders.HTTP_VERSION + "\r\n" + HttpHeaders.Create(HttpHeaders.HOST, dns.Hostname) + HttpHeaders.Create(HttpHeaders.CONNECTION, HttpHeaders.UPGRADE) + HttpHeaders.Create(HttpHeaders.PRAGMA, HttpHeaders.VALUE_NO_CACHE) + HttpHeaders.Create(HttpHeaders.CACHE_CONTROL, HttpHeaders.VALUE_NO_CACHE) + HttpHeaders.Create(HttpHeaders.UPGRADE, HttpHeaders.VALUE_WEBSOCKET) + HttpHeaders.Create(HttpHeaders.WEBSOCKET_VERSION, HttpHeaders.VALUE_WEBSOCKET_VERSION) + HttpHeaders.Create(HttpHeaders.ACCEPT_ENCODING, HttpHeaders.VALUE_GZIP_DEFLATE_BR) + HttpHeaders.Create(HttpHeaders.ACCEPT_LANGUAGE, HttpHeaders.VALUE_ACCEPT_EN) + HttpHeaders.Create(HttpHeaders.WEBSOCKET_KEY, WebSocketKey) + HttpHeaders.Create(HttpHeaders.WEBSOCKET_EXTENSIONS, HttpHeaders.VALUE_WEBSOCKET_EXTENSIONS); lock (Data) foreach (var kv in Data.Properties) { request += HttpHeaders.Create(kv.Key, kv.Value); } request += "\r\n"; return(Encoding.UTF8.GetBytes(request)); }
public override async Task <AbstractRobot[]> PripojeniRoboti() { if (EnterpriseManagerClient == null) { Connect(); } var identifikatoryRobotuPripojenychNaServer = EnterpriseManagerClient.RefreshConnectedRobots(); await Task.Delay(10); LynxModel[] vysledek = new LynxModel[identifikatoryRobotuPripojenychNaServer.Where(x => x != null).Count()]; int indexPole = 0; foreach (string identifikator in identifikatoryRobotuPripojenychNaServer) { DnsInfo robotDnsInfo = GetHostNameAndIPAdress.DnsInfoFromHostname($"AGV_{identifikator}"); LynxModel pripojenyRobot = new LynxModel { Hostname = identifikator, IpAdress = robotDnsInfo.IP.ToString() }; vysledek[indexPole] = pripojenyRobot; indexPole++; } return(vysledek); }
public void NajdiIpAdresuRobota() { string hostname = "AGV_Luky"; DnsInfo info = GetHostNameAndIPAdress.DnsInfoFromHostname(hostname); Assert.IsTrue(info.IP.ToString() == "10.226.178.252"); }
public bool Connect(DnsInfo dns) { try { Client = new TcpClient(); Client.Connect(dns.IPAddress, dns.Port); IsConnected = true; if (dns.SSL) { Stream = new SslStream(Client.GetStream(), true); } else { Stream = Client.GetStream(); } byte[] request = CreateRequest(dns); Stream.Write(request, 0, request.Length); byte[] buffer = new byte[8192]; int len = Stream.Read(buffer, 0, buffer.Length); string response = Encoding.UTF8.GetString(buffer, 0, len); string first = response.Substring(0, 50); if (!first.Contains(" 101 ")) { Disconnect(); throw new NotSupportedException("Server doesn't support web socket protocol"); } RequestReader reader = new RequestReader(); HttpRequest requestResponse = reader.Read(response); if (!requestResponse.Headers.ContainsKey("Sec-WebSocket-Accept")) { throw new InvalidOperationException("Handshaking error, server didn't response Sec-WebSocket-Accept"); } string rkey = requestResponse.Headers["Sec-WebSocket-Accept"]; using (SHA1 sha1 = SHA1.Create()) { byte[] hash = sha1.ComputeHash(Encoding.UTF8.GetBytes(WebSocketKey + HttpServer.WEBSOCKET_GUID)); string fkey = Convert.ToBase64String(hash); if (rkey != fkey) { throw new InvalidOperationException("Handshaking error, Invalid Key"); } } OnConnected(); Task.Factory.StartNew(Read); return(true); } catch { Disconnect(); return(false); } }
public bool Connect(string uri) { DnsResolver resolver = new DnsResolver(); DnsInfo info = resolver.Resolve(uri); return(Connect(info)); }
public void TestUpdateDnsTxt() { var dnsInfo = DnsInfo.Load(File.ReadAllText("config\\dnsInfo.json")); dnsInfo.Provider.EditTxtRecord( $"_acme-challenge.foo1.{dnsInfo.DefaultDomain}", new string[] { $"{Environment.UserName}@{Environment.MachineName}@{DateTime.Now}" }); dnsInfo.Provider.EditTxtRecord( $"_acme-challenge.foo2.{dnsInfo.DefaultDomain}", new string[] { Environment.UserName, Environment.MachineName, DateTime.Now.ToString() }); }
public bool Connect(string ip, int port, bool secure) { DnsInfo info = new DnsInfo { IPAddress = ip, Hostname = ip, Port = port, Path = "/", Protocol = Protocol.WebSocket, SSL = secure }; return(Connect(info)); }
/// <summary> /// Connects to well defined remote host /// </summary> public override async Task ConnectAsync(DnsInfo host) { try { Client = new TcpClient(); await Client.ConnectAsync(host.IPAddress, host.Port); IsConnected = true; IsSsl = host.SSL; //creates SSL Stream or Insecure stream if (host.SSL) { SslStream sslStream = new SslStream(Client.GetStream(), true, CertificateCallback); X509Certificate2Collection certificates = null; if (Certificate != null) { certificates = new X509Certificate2Collection(); certificates.Add(Certificate); } await sslStream.AuthenticateAsClientAsync(host.Hostname, certificates, false); Stream = sslStream; } else { Stream = Client.GetStream(); } //creates new HTTP Request and sends via Stream byte[] request = CreateRequest(host); await Stream.WriteAsync(request); //Reads the response. Expected response is 101 Switching Protocols (if the server supports web sockets) byte[] buffer = new byte[8192]; int len = await Stream.ReadAsync(buffer, 0, buffer.Length); CheckProtocolResponse(buffer, len); Start(); } catch { Disconnect(); throw; } }
public void Test0130_HandleDnsChallenge() { using (var signer = new RS256Signer()) { signer.Init(); using (var fs = new FileStream($"{BASE_LOCAL_STORE}TestRegister.acmeSigner", FileMode.Open)) { signer.Load(fs); } AcmeRegistration reg; using (var fs = new FileStream($"{BASE_LOCAL_STORE}TestRegister.acmeReg", FileMode.Open)) { reg = AcmeRegistration.Load(fs); } using (var client = BuildClient()) { client.RootUrl = _rootUrl; client.Signer = signer; client.Registration = reg; client.Init(); client.GetDirectory(true); AuthorizationState authzState; using (var fs = new FileStream($"{BASE_LOCAL_STORE}TestAuthz.acmeAuthz", FileMode.Open)) { authzState = AuthorizationState.Load(fs); } var authzChallenge = client.GenerateAuthorizeChallengeAnswer(authzState, "dns"); using (var fs = new FileStream($"{BASE_LOCAL_STORE}TestAuthz-ChallengeAnswersHandleDns.acmeAuthz", FileMode.Create)) { authzState.Save(fs); } var dnsName = authzChallenge.ChallengeAnswer.Key; var dnsValue = Regex.Replace(authzChallenge.ChallengeAnswer.Value, "\\s", ""); var dnsValues = Regex.Replace(dnsValue, "(.{100,100})", "$1\n").Split('\n'); var dnsInfo = DnsInfo.Load(File.ReadAllText("dnsInfo.json")); dnsInfo.Provider.EditTxtRecord(dnsName, dnsValues); } } Thread.Sleep(90 * 1000); }
private byte[] CreateRequest(DnsInfo dns) { using (SHA1 sha1 = SHA1.Create()) { byte[] hash = sha1.ComputeHash(Guid.NewGuid().ToByteArray()); WebSocketKey = Convert.ToBase64String(hash); } string request = "GET " + dns.Path + " HTTP/1.1" + Environment.NewLine + "Host: " + dns.Hostname + Environment.NewLine + "Connection: Upgrade" + Environment.NewLine + "Pragma: no-cache" + Environment.NewLine + "Cache-Control: no-cache" + Environment.NewLine + "Upgrade: websocket" + Environment.NewLine + "Sec-WebSocket-Version: 13" + Environment.NewLine + "Accept-Encoding: gzip, deflate, br" + Environment.NewLine + "Accept-Language: en-US,en;q=0.9" + Environment.NewLine + "Sec-WebSocket-Key: " + WebSocketKey + Environment.NewLine + "Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits" + Environment.NewLine; request += Environment.NewLine; return(Encoding.UTF8.GetBytes(request)); }
public override string ToString() { var sb = new StringBuilder(); sb.AppendLine($"File Name {FileName}"); sb.AppendLine(); if (RoleAccesses.Any()) { sb.AppendLine($"** ROLE ACCESSES **"); foreach (var ra in RoleAccesses) { sb.AppendLine(ra.ToString()); } sb.AppendLine(); } else { sb.AppendLine("!!!! No Role Accesses present !!!!\r\n"); } if (VmInfo.Any()) { sb.AppendLine($"** VIRTUAL MACHINES **"); foreach (var vm in VmInfo) { sb.AppendLine(vm.ToString()); } sb.AppendLine(); } else { sb.AppendLine("!!!! No VM Info present !!!!\r\n"); } if (DnsInfo.Any()) { sb.AppendLine($"** DNS INFO **"); foreach (var dns in DnsInfo) { sb.AppendLine(dns.ToString()); } sb.AppendLine(); } else { sb.AppendLine("!!!! No DNS Info present !!!!\r\n"); } if (Clients.Any()) { sb.AppendLine($"** CLIENTS **"); foreach (var client in Clients) { sb.AppendLine($"Role Guid: {client.Key}"); foreach (var clientEntry in client.Value) { sb.AppendLine(clientEntry.ToString()); } } sb.AppendLine(); } else { sb.AppendLine("!!!! No Client Info present !!!!\r\n"); } return(sb.ToString()); }
protected override void ProcessRecord() { using (var vp = InitializeVault.GetVaultProvider(VaultProfile)) { vp.OpenStorage(); var v = vp.LoadVault(); if (v.Registrations == null || v.Registrations.Count < 1) { throw new InvalidOperationException("No registrations found"); } var ri = v.Registrations[0]; var r = ri.Registration; if (v.Identifiers == null || v.Identifiers.Count < 1) { throw new InvalidOperationException("No identifiers found"); } var ii = v.Identifiers.GetByRef(Ref); if (ii == null) { throw new Exception("Unable to find an Identifier for the given reference"); } var authzState = ii.Authorization; if (ii.Challenges == null) { ii.Challenges = new Dictionary <string, AuthorizeChallenge>(); } if (ii.ChallengeCompleted == null) { ii.ChallengeCompleted = new Dictionary <string, DateTime?>(); } if (v.ProviderConfigs == null || v.ProviderConfigs.Count < 1) { throw new InvalidOperationException("No provider configs found"); } var pc = v.ProviderConfigs.GetByRef(ProviderConfig); if (pc == null) { throw new InvalidOperationException("Unable to find a Provider Config for the given reference"); } AuthorizeChallenge challenge = null; DateTime? challengCompleted = null; ii.Challenges.TryGetValue(Challenge, out challenge); ii.ChallengeCompleted.TryGetValue(Challenge, out challengCompleted); if (challenge == null || Regenerate) { using (var c = ClientHelper.GetClient(v, ri)) { c.Init(); c.GetDirectory(true); challenge = c.GenerateAuthorizeChallengeAnswer(authzState, Challenge); ii.Challenges[Challenge] = challenge; } } if (Repeat || challengCompleted == null) { var pcFilePath = $"{pc.Id}.json"; var pcAsset = vp.GetAsset(Vault.VaultAssetType.ProviderConfigInfo, pcFilePath); // TODO: There's *way* too much logic buried in here // this needs to be refactored and extracted out to be // more manageble and more reusable if (Challenge == AcmeProtocol.CHALLENGE_TYPE_DNS) { if (string.IsNullOrEmpty(pc.DnsProvider)) { throw new InvalidOperationException("Referenced Provider Configuration does not support the selected Challenge"); } var dnsName = challenge.ChallengeAnswer.Key; var dnsValue = Regex.Replace(challenge.ChallengeAnswer.Value, "\\s", ""); var dnsValues = Regex.Replace(dnsValue, "(.{100,100})", "$1\n").Split('\n'); using (var s = vp.LoadAsset(pcAsset)) // new FileStream(pcFilePath, FileMode.Open)) { var dnsInfo = DnsInfo.Load(s); dnsInfo.Provider.EditTxtRecord(dnsName, dnsValues); ii.ChallengeCompleted[Challenge] = DateTime.Now; } } else if (Challenge == AcmeProtocol.CHALLENGE_TYPE_HTTP) { if (string.IsNullOrEmpty(pc.WebServerProvider)) { throw new InvalidOperationException("Referenced Provider Configuration does not support the selected Challenge"); } var wsFilePath = challenge.ChallengeAnswer.Key; var wsFileBody = challenge.ChallengeAnswer.Value; var wsFileUrl = new Uri($"http://{authzState.Identifier}/{wsFilePath}"); using (var s = vp.LoadAsset(pcAsset)) // new FileStream(pcFilePath, FileMode.Open)) { var webServerInfo = WebServerInfo.Load(s); using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(wsFileBody))) { webServerInfo.Provider.UploadFile(wsFileUrl, ms); ii.ChallengeCompleted[Challenge] = DateTime.Now; } } } } vp.SaveVault(v); WriteObject(authzState); } }