/// <summary>Create a DtlsFilter.</summary> /// <param name="key">A CryptoKey initialized by the OpenSSL.NET library.</param> /// <param name="cert">The path to the certificate to use.</param> /// <param name="ca_cert">The path to the ca certificate to use.</param> /// <param name="client">Use client initialization parameters.</param> public DtlsAssociation(ISender sender, CertificateHandler ch, PType ptype, Ssl ssl, bool client) : base(sender, ch) { _ip = new IdentifierPair(); PType = ptype; _ssl = ssl; _client = client; _ssl.SetReadAhead(1); // Buggy SSL versions have issue with compression and dtls _ssl.SetOptions((int)SslOptions.SSL_OP_NO_COMPRESSION); if (client) { _ssl.SetConnectState(); } else { _ssl.SetAcceptState(); } // The ssl object will take control _read = BIO.MemoryBuffer(false); _read.NonBlocking = true; _write = BIO.MemoryBuffer(false); _write.NonBlocking = true; _ssl.SetBIO(_read, _write); _ssl.DoHandshake(); _buffer = new byte[Int16.MaxValue]; _buffer_sync = new object(); _fe_lock = 0; }
public void TearDownCertificateTests() { CertificateLogsHandler.DeleteRecord(_createdCertificate.Id); CertificateHandler.DeleteRecord(_createdCertificate.Id); OrganisationHandler.DeleteRecordByEndPointAssessorOrganisationId("EPA0200"); OrganisationTypeHandler.DeleteRecord(_organisationTypeId); }
/// <summary></summary> public SecurityOverlord(RSACryptoServiceProvider private_key, CertificateHandler ch) { _private_key = private_key; _ch = ch; _stopped = 0; _sa_check = FuzzyTimer.Instance.DoEvery(CheckSAs, CHECK_SA_PERIOD, 0);//CHECK_SA_PERIOD / 2); }
public PeerSecAssociation(ISender sender, CertificateHandler ch, int spi) : base(sender, ch) { _called_start = 0; _closed = 0; _active = false; _spi = spi; _state = States.Waiting; Reset(); }
protected virtual bool ValidateServiceCertificate( HttpRequestMessage message, X509Certificate2 certificate, X509Chain chain, SslPolicyErrors errors, IEnumerable <Certificate> pinned ) { return(CertificateHandler.ValidateCertificate(certificate, chain, errors, pinned)); }
/// <summary></summary> public SecurityAssociation(ISender sender, CertificateHandler ch) { Sender = sender; _ch = ch; _closed = 0; _receiving = true; _sending = true; _state = States.Waiting; _state_lock = new object(); }
public PeerSecAssociation(ISender sender, CertificateHandler ch, int spi) : base(sender, ch) { _closed = 0; _active = false; _spi = spi; _last_update = DateTime.MinValue; _state = States.Waiting; Reset(); }
private void Awake() { if (instance != null && instance != this) { Destroy(this.gameObject); return; } instance = this; certHandler = new CustomCertificateHandler(); }
public SymphonySecurityOverlord(Node node, RSACryptoServiceProvider rsa, CertificateHandler ch, ReqrepManager rrman) : base(rsa, ch, rrman) { _ch.AddCertificateVerification(new SymphonyVerification(ch)); _node = node; _address_to_sa = new Dictionary <Address, SecurityAssociation>(); _sa_to_address = new Dictionary <SecurityAssociation, Address>(); lock (_sync) { _node.Rpc.AddHandler("Security", this); } }
public SymphonySecurityOverlord(Node node, RSACryptoServiceProvider rsa, CertificateHandler ch, ReqrepManager rrman) : base(rsa, ch, rrman) { _ch.AddCertificateVerification(new SymphonyVerification(node.ConnectionTable)); _node = node; _address_to_sa = new Dictionary<Address, SecurityAssociation>(); _sa_to_address = new Dictionary<SecurityAssociation, Address>(); lock(_sync) { _node.Rpc.AddHandler("Security", this); } }
public PeerSecOverlord(RSACryptoServiceProvider rsa, CertificateHandler ch, ReqrepManager rrman) : base(rsa, ch) { _private_key_lock = new object(); _spi = new Dictionary <int, Dictionary <ISender, PeerSecAssociation> >(); _cookie = new byte[CookieLength]; _rand = new Random(); _rand.NextBytes(_cookie); _rrman = rrman; _last_heartbeat = DateTime.UtcNow; _rrman.Subscribe(this, null); }
public ProtocolSecurityOverlord(Node node, RSACryptoServiceProvider rsa, ReqrepManager rrman, CertificateHandler ch) : base(rsa, rrman, ch) { _node = node; _address_to_sa = new Dictionary <Address, SecurityAssociation>(); _sa_to_address = new Dictionary <SecurityAssociation, Address>(); lock (_sync) { _node.Rpc.AddHandler("Security", this); } }
public async Task RenewCert() { ThrowIfDisposed(); string machineName = Environment.OSVersion + " - " + Environment.MachineName; byte[][] key = CertificateHandler.GenerateKeyPair(); mes.SendMessage(new Message(Message.MessageType.CertRenewRequest, false, key[0], key[1], machineName)); Message rec = await mes.WaitForMessageAsync(true, Message.MessageType.CertRenewSuccess); CertificateHandler.NewCertificate(rec[0]); }
public void ConfigureSslCert_CertHasExpiredOutsideRenewThreshold_Renewed() { DeleteConDepCertificates(); try { var certificate = CreateCertificate(-8); AddToStore(certificate); CertificateHandler.ConfigureSslCert("https://localhost:4444/ConDepNode/"); var certificatesFromStore = GetCertificates(); var renewedCertificate = certificatesFromStore[0]; Assert.AreNotEqual(renewedCertificate.Thumbprint, certificate.Thumbprint); } finally { DeleteConDepCertificates(); } }
public async Task <bool> AuthWithPass(string username, string password) { ThrowIfDisposed(); try { string machineName = Environment.OSVersion + " - " + Environment.MachineName; byte[][] key = CertificateHandler.GenerateKeyPair(); mes.SendMessage(new Message(Message.MessageType.CertRequest, false, username, password, key[0], key[1], machineName)); Message rec = await mes.WaitForMessageAsync(false); if (rec.IsError == true) { throw new Exception("Recived an error: " + rec.ToString()); } else if (rec.Type == Message.MessageType.CertSuccess) { CertificateHandler.NewCertificate(rec[0]); return(true); } else if (rec.Type == Message.MessageType.TwoFactorNeeded) { //Two fa needed await DoTwoFaExchangeAsync(); return(true); } else { //unexpected message throw new Exception("Unexpected message: " + rec.ToString()); } } catch (SequenceBreakException e) { mes.SendMessage(new Message(Message.MessageType.Sequence, true)); log.Info(e); return(false); } catch (Exception e) { log.Info(e); return(false); } }
/// <summary> /// Rest POST. /// </summary> /// <param name="query">Finalized Endpoint Query with parameters.</param> /// <param name="headers">Optional header information for the request.</param> /// <param name="timeout">Optional time in seconds before request expires.</param> /// <param name="readResponseData">Optional bool. If its true, response data will be read from web request download handler.</param> /// <param name="certificateHandler">Optional certificate handler for custom certificate verification</param> /// <param name="disposeCertificateHandlerOnDispose">Optional bool. If true and <paramref name="certificateHandler"/> is not null, <paramref name="certificateHandler"/> will be disposed, when the underlying UnityWebRequest is disposed.</param> /// <returns>The response data.</returns> public static async Task <Response> PostAsync( string query, Dictionary <string, string> headers = null, int timeout = -1, bool readResponseData = false, CertificateHandler certificateHandler = null, bool disposeCertificateHandlerOnDispose = true, CancellationToken cancellationToken = default(CancellationToken)) { using (var webRequest = UnityWebRequest.Post(query, null as string)) { cancellationToken.Register(() => { webRequest.Abort(); }); return(await ProcessRequestAsync(webRequest, timeout, headers, readResponseData, certificateHandler, disposeCertificateHandlerOnDispose)); } }
void Awake() { if (instance != null && instance != this) { Destroy(this.gameObject); return; } else { instance = this; } LoadPrefs(); //DontDestroyOnLoad(instance.gameObject); certHandler = new CustomCertificateHandler(); }
public void ConfigureSslCert_IfCertDoesNotExpireWithin7Days_NotRenewed() { DeleteConDepCertificates(); try { var certificate = CreateCertificate(8); AddToStore(certificate); CertificateHandler.ConfigureSslCert("https://localhost:4444/ConDepNode/"); var certificatesFromStore = GetCertificates(); Console.WriteLine("certificatesFromStore.Count: " + certificatesFromStore.Count); var certificateFromStore = certificatesFromStore[0]; Assert.AreEqual(certificate.Thumbprint, certificateFromStore.Thumbprint); } finally { DeleteConDepCertificates(); } }
public void ConfigureSslCert_IfCertExpiresWithin7Days_Renewed() { DeleteConDepCertificates(); try { var certificate = CreateCertificate(5); AddToStore(certificate); CertificateHandler.ConfigureSslCert("https://localhost:4444/ConDepNode/"); var certificatesFromStore = GetCertificates(); var expiryDateOfCertificate = certificatesFromStore[0].NotAfter; var expectedExpiryDateOfCertificate = expiryDateOfCertificate.AddDays(365); Assert.That(Math.Abs((expectedExpiryDateOfCertificate - expiryDateOfCertificate).TotalDays - 365) < Epsilon); Assert.That(certificatesFromStore.Count == 1); } finally { DeleteConDepCertificates(); } }
/// <summary> /// Rest PUT. /// </summary> /// <param name="query">Finalized Endpoint Query with parameters.</param> /// <param name="bodyData">Data to be submitted.</param> /// <param name="headers">Optional header information for the request.</param> /// <param name="timeout">Optional time in seconds before request expires.</param> /// <param name="readResponseData">Optional bool. If its true, response data will be read from web request download handler.</param> /// <param name="certificateHandler">Optional certificate handler for custom certificate verification</param> /// <param name="disposeCertificateHandlerOnDispose">Optional bool. If true and <paramref name="certificateHandler"/> is not null, <paramref name="certificateHandler"/> will be disposed, when the underlying UnityWebRequest is disposed.</param> /// <returns>The response data.</returns> public static async Task <Response> PutAsync( string query, byte[] bodyData, Dictionary <string, string> headers = null, int timeout = -1, bool readResponseData = false, CertificateHandler certificateHandler = null, bool disposeCertificateHandlerOnDispose = true, CancellationToken cancellationToken = default(CancellationToken)) { using (var webRequest = UnityWebRequest.Put(query, bodyData)) { cancellationToken.Register(() => { webRequest.Abort(); }); webRequest.SetRequestHeader("Content-Type", "application/octet-stream"); return(await ProcessRequestAsync(webRequest, timeout, headers, readResponseData, certificateHandler, disposeCertificateHandlerOnDispose)); } }
public void ValidityTest() { var osch = new OpenSslCertificateHandler(); RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(512); byte[] blob = rsa.ExportCspBlob(false); RSACryptoServiceProvider rsa_pub = new RSACryptoServiceProvider(); rsa_pub.ImportCspBlob(blob); string ID = "brunet:node:PXYSWDL5SZDHDDXJKZCLFENOP2KZDMBU"; CertificateMaker cm = new CertificateMaker("US", "UFL", "ACIS", "David Wolinsky", "*****@*****.**", rsa_pub, ID); Certificate cert_0 = cm.Sign(cm, rsa); osch.AddSignedCertificate(cert_0.X509); osch.AddCACertificate(cert_0.X509); var ocert = OpenSslCertificateHandler.OpenSslX509ToMonoX509(osch.LocalCertificate); Assert.AreEqual(cert_0.X509.RawData, ocert.RawData, "local check"); Assert.IsTrue(CertificateHandler.Verify(ocert, ID), "Valid"); }
protected PeerSecOverlord CreateInvalidSO(string name, int level) { if (rsa == null) { rsa = new RSACryptoServiceProvider(); byte[] blob = rsa.ExportCspBlob(false); RSACryptoServiceProvider rsa_pub = new RSACryptoServiceProvider(); rsa_pub.ImportCspBlob(blob); CertificateMaker cm = new CertificateMaker("United States", "UFL", "ACIS", "David Wolinsky", "*****@*****.**", rsa_pub, "brunet:node:abcdefghijklmnopqrs"); Certificate cert = cm.Sign(cm, rsa); x509 = cert.X509; } CertificateHandler ch = new CertificateHandler(); if (level == 2 || level == 0) { ch.AddCACertificate(x509); } if (level == 3 || level == 0) { ch.AddSignedCertificate(x509); } Random rand = new Random(); ReqrepManager rrm = new ReqrepManager("so" + name + rand.Next()); _timeout += rrm.TimeoutChecker; PeerSecOverlord so = new PeerSecOverlord(rsa_safe, ch, rrm); so.AnnounceSA += AnnounceSA; RoutingDataHandler rdh = new RoutingDataHandler(); rrm.Subscribe(so, null); so.Subscribe(rdh, null); rdh.Subscribe(rrm, null); return(so); }
/// <summary></summary> public DtlsOverlord(RSACryptoServiceProvider private_key, CertificateHandler ch, PType ptype) : base(private_key, ch) { _osch = ch as OpenSslCertificateHandler; if (_osch == null) { throw new Exception("CertificateHandler is invalid type: " + ch.GetType()); } _it = new IdentifierTable(); _sas_helper = new IdentifierTableAsDtlsAssociation(_it); _rwl = new ReaderWriterLock(); _sender_to_sa = new Dictionary <ISender, DtlsAssociation>(); PType = ptype; _ptype_mb = ptype.ToMemBlock(); _ctx = new SslContext(SslMethod.DTLSv1_method); _ctx.SetCertificateStore(_osch.Store); _ctx.SetVerify(VerifyMode.SSL_VERIFY_PEER | VerifyMode.SSL_VERIFY_FAIL_IF_NO_PEER_CERT, RemoteCertificateValidation); _ctx.UsePrivateKey(AsymmetricKeyToOpenSslFormat(_private_key)); _ctx.UseCertificate(_osch.LocalCertificate); _ctx.CheckPrivateKey(); _ctx.Options = SslOptions.SSL_OP_SINGLE_DH_USE; var rng = new RNGCryptoServiceProvider(); byte[] sid = new byte[4]; rng.GetBytes(sid); _ctx.SetSessionIdContext(sid); _ctx.SetCookieGenerateCallback(GenerateCookie); _ctx.SetCookieVerifyCallback(VerifyCookie); _ctx.Options = SslOptions.SSL_OP_COOKIE_EXCHANGE; UpdateCookie(); }
/// <summary> /// Method creates IPGAPI Order request, sends it and recieves IPG API Order Response /// </summary> /// <param name="oIPGApiOrderRequest"></param> /// <returns>IPG API Order Response as string</returns> private static String SendOrderRequest(IPGApiOrderRequest oIPGApiOrderRequest) { var cert = CertificateHandler.LoadCertificate(@"c:\certificates\WS120995000._.4.p12", "tester02"); IPGApiOrderService oIPGApiOrderService = new IPGApiOrderService(); String RequestResponseMessage = ""; if (cert != null) { oIPGApiOrderService.ClientCertificates.Add(cert); oIPGApiOrderService.Url = @"https://test.ipg-online.com:443/ipgapi/services"; NetworkCredential nc = new NetworkCredential("WS120995000._.4", "Tester02"); oIPGApiOrderService.Credentials = nc; //set proxy host and port IWebProxy webProxy = new WebProxy("host", 8080); webProxy.Credentials = new NetworkCredential("username", "password"); oIPGApiOrderService.Proxy = webProxy; try { //send action request and get response IPGApiOrderResponse oResponse = oIPGApiOrderService.IPGApiOrder(oIPGApiOrderRequest); RequestResponseMessage = oResponse.IPGApiOrderResponseToString() ?? ""; } catch (SoapException se) {//SoapException: MerchantException or ProcessingException RequestResponseMessage = se.SoapExceptionResponseToString() ?? ""; } catch (Exception e) { RequestResponseMessage = e.Message + Environment.NewLine; RequestResponseMessage += e.InnerException + Environment.NewLine; RequestResponseMessage += e.StackTrace; } } return(RequestResponseMessage); }
public static IWebHostBuilder CreateBuilder <T>(string[] args) where T : class, new() { return(WebHost.CreateDefaultBuilder(args) .UseStartup <T>() .UseKestrel(options => { var server = ServiceStartup.Configuration.GetSection("Server").Get <Server>(); options.Listen(IPAddress.Loopback, server.Port, listenOptions => { var certificate = FindServerCertificate(server); listenOptions.UseHttps(new HttpsConnectionAdapterOptions() { ServerCertificate = certificate, ClientCertificateMode = ClientCertificateMode.RequireCertificate, SslProtocols = SslProtocols.Tls12, ClientCertificateValidation = (a, b, c) => CertificateHandler.ValidateCertificate(a, b, c, server.ClientCertificates) }); }); })); }
/// <summary> /// Rest POST. /// </summary> /// <param name="query">Finalized Endpoint Query with parameters.</param> /// <param name="jsonData">JSON data for the request.</param> /// <param name="headers">Optional header information for the request.</param> /// <param name="timeout">Optional time in seconds before request expires.</param> /// <param name="readResponseData">Optional bool. If its true, response data will be read from web request download handler.</param> /// <param name="certificateHandler">Optional certificate handler for custom certificate verification</param> /// <param name="disposeCertificateHandlerOnDispose">Optional bool. If true and <paramref name="certificateHandler"/> is not null, <paramref name="certificateHandler"/> will be disposed, when the underlying UnityWebRequest is disposed.</param> /// <returns>The response data.</returns> public static async Task <Response> PostAsync( string query, string jsonData, Dictionary <string, string> headers = null, int timeout = -1, bool readResponseData = false, CertificateHandler certificateHandler = null, bool disposeCertificateHandlerOnDispose = true, CancellationToken cancellationToken = default(CancellationToken)) { using (var webRequest = UnityWebRequest.Post(query, "POST")) { cancellationToken.Register(() => { webRequest.Abort(); }); var data = new UTF8Encoding().GetBytes(jsonData); webRequest.uploadHandler = new UploadHandlerRaw(data); webRequest.downloadHandler = new DownloadHandlerBuffer(); webRequest.SetRequestHeader("Content-Type", "application/json"); webRequest.SetRequestHeader("Accept", "application/json"); return(await ProcessRequestAsync(webRequest, timeout, headers, readResponseData, certificateHandler, disposeCertificateHandlerOnDispose)); } }
IEnumerator SendMsg() // Post 방식 서버 연동 { //List<IMultipartFormSection> formData = new List<IMultipartFormSection>(); //formData.Add(new MultipartFormDataSection("x=128.622397&y=34.889456&radius=500")); ////formData.Add(new MultipartFormDataSection("my file data, myfile.txt")); // 파일도 보낼 수 있나봄 WWWForm formData = new WWWForm(); formData.AddField("x", "128.595835"); formData.AddField("y", "35.869171"); formData.AddField("radius", 100); cert = new ForceAcceptAll(); UnityWebRequest www = UnityWebRequest.Post("https://api1.codns.com:80/get_surroundings", formData); www.certificateHandler = cert; yield return(www.SendWebRequest()); if (www.isNetworkError || www.isHttpError) { res.text = www.error; Debug.Log(www.error); } else { res.text = www.downloadHandler.text; Debug.Log(res.text); JsonData obj = JsonMapper.ToObject(res.text); for (int i = 0; i < obj["contents"].Count; i++) { //Debug.Log(obj["contents"][i]); } //cert.Dispose(); } }
public Client(TcpClient tcp, DatabaseHandler db, ILogger <Client> log, CertificateHandler handler, bool verbose) { log.LogInformation("Client born"); Tcp = tcp; this.db = db; this.log = log; certificateHandler = handler; stream = new SslStream(tcp.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate), new LocalCertificateSelectionCallback(Selection)); stream.AuthenticateAsServer(handler.Certificate, true, false); mes = new MessageHandler(tcp, stream, verbose, new MessageLogger(log)); mes.OnDisconnect += OnDisconnect; mes.Start(); if (verificationResult == VerificationResult.Valid || verificationResult == VerificationResult.ValidArchival) { try { db.SetUser(verificationSerial); IsAuthenticated = true; mes.SendMessage(new Message(Message.MessageType.AuthSuccess, false, db.Name)); } catch (KeyNotFoundException) { mes.SendMessage(new Message(Message.MessageType.AuthSuccess, true)); } } log.LogDebug("Encryption established"); log.LogDebug("Client initialized"); }
/// <summary> /// Rest GET. /// </summary> /// <param name="query">Finalized Endpoint Query with parameters.</param> /// <param name="headers">Optional header information for the request.</param> /// <param name="timeout">Optional time in seconds before request expires.</param> /// <param name="downloadHandler">Optional DownloadHandler for the request.</param> /// <param name="readResponseData">Optional bool. If its true, response data will be read from web request download handler.</param> /// <param name="certificateHandler">Optional certificate handler for custom certificate verification</param> /// <param name="disposeCertificateHandlerOnDispose">Optional bool. If true and <paramref name="certificateHandler"/> is not null, <paramref name="certificateHandler"/> will be disposed, when the underlying UnityWebRequest is disposed.</param> /// <returns>The response data.</returns> public static async Task <Response> GetAsync(string query, Dictionary <string, string> headers = null, int timeout = -1, DownloadHandler downloadHandler = null, bool readResponseData = false, CertificateHandler certificateHandler = null, bool disposeCertificateHandlerOnDispose = true) { using (var webRequest = UnityWebRequest.Get(query)) { if (downloadHandler != null) { webRequest.downloadHandler = downloadHandler; } return(await ProcessRequestAsync(webRequest, timeout, headers, readResponseData, certificateHandler, disposeCertificateHandlerOnDispose)); } }
public void ValidityTest() { CertificateHandler ch = new CertificateHandler(); RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(512); byte[] blob = rsa.ExportCspBlob(false); RSACryptoServiceProvider rsa_pub = new RSACryptoServiceProvider(); rsa_pub.ImportCspBlob(blob); string ID = "brunet:node:PXYSWDL5SZDHDDXJKZCLFENOP2KZDMBU"; CertificateMaker cm = new CertificateMaker("US", "UFL", "ACIS", "David Wolinsky", "*****@*****.**", rsa_pub, ID); Certificate cert_0 = cm.Sign(cm, rsa); ch.AddSignedCertificate(cert_0.X509); ch.AddCACertificate(cert_0.X509); rsa = new RSACryptoServiceProvider(1024); rsa_pub.ImportCspBlob(rsa.ExportCspBlob(false)); cm = new CertificateMaker("US", "UFL", "ACIS", "David Wolinsky", "*****@*****.**", rsa_pub, ID); Certificate cert_1 = cm.Sign(cm, rsa); Assert.IsTrue(ch.Verify(cert_0.X509, ID), "Valid"); bool success = false; try { success = ch.Verify(cert_1.X509, ID); } catch { } Assert.IsTrue(!success, "Valid cert2"); }
// adds a node to the pool protected static void add_node(bool output) { AHAddress address = new AHAddress(new RNGCryptoServiceProvider()); Node node = new StructuredNode(address, brunet_namespace); NodeMapping nm = new NodeMapping(); nm.Node = node; nodes.Add((Address) address, nm); nm.Port = TakenPorts.Count; while(TakenPorts.Contains(nm.Port)) { nm.Port = rand.Next(0, 65535); } TAAuthorizer auth = null; if(broken != 0) { auth = new BrokenTAAuth(broken); } EdgeListener el = new SimulationEdgeListener(nm.Port, 0, auth, true); if(secure_edges || secure_senders) { byte[] blob = SEKey.ExportCspBlob(true); RSACryptoServiceProvider rsa_copy = new RSACryptoServiceProvider(); rsa_copy.ImportCspBlob(blob); CertificateMaker cm = new CertificateMaker("United States", "UFL", "ACIS", "David Wolinsky", "*****@*****.**", rsa_copy, address.ToString()); Certificate cert = cm.Sign(CACert, SEKey); CertificateHandler ch = new CertificateHandler(); ch.AddCACertificate(CACert.X509); ch.AddSignedCertificate(cert.X509); BrunetSecurityOverlord so = new BrunetSecurityOverlord(node, rsa_copy, node.Rrm, ch); so.Subscribe(node, null); node.GetTypeSource(SecurityOverlord.Security).Subscribe(so, null); nm.BSO = so; node.HeartBeatEvent += so.Heartbeat; } if(secure_edges) { el = new SecureEdgeListener(el, nm.BSO); } node.AddEdgeListener(el); if(broken != 0) { el = new TunnelEdgeListener(node); node.AddEdgeListener(el); } ArrayList RemoteTAs = new ArrayList(); for(int i = 0; i < 5 && i < TakenPorts.Count; i++) { int rport = (int) TakenPorts.GetByIndex(rand.Next(0, TakenPorts.Count)); RemoteTAs.Add(TransportAddressFactory.CreateInstance("brunet.function://127.0.0.1:" + rport)); } node.RemoteTAs = RemoteTAs; TakenPorts[nm.Port] = nm.Port; if(output) { Console.WriteLine("Adding: " + nm.Node.Address); } node.Connect(); network_size++; }
/** <summary>Creates a Brunet.Node, the resulting node will be available in the class as _node.</summary> <remarks>The steps to creating a node are first constructing it with a namespace, optionally adding local ip addresses to bind to, specifying local end points, specifying remote end points, and finally registering the dht.</remarks> */ public virtual void CreateNode(string type) { NodeConfig node_config = null; StructuredNode current_node = null; AHAddress address = null; ProtocolSecurityOverlord bso; if (type == "cache") { node_config = _c_node_config; //Node configuration file: the description of service that node provides address = (AHAddress) AddressParser.Parse(node_config.NodeAddress); current_node = new StructuredNode(address, node_config.BrunetNamespace); // DeetooNode consists of two Structured Nodes bso = _c_bso; } else if ( type == "query" ) { node_config = _q_node_config; address = (AHAddress) AddressParser.Parse(node_config.NodeAddress); current_node = new StructuredNode(address, node_config.BrunetNamespace); bso = _q_bso; } else { throw new Exception("Unrecognized node type: " + type); } IEnumerable addresses = IPAddresses.GetIPAddresses(node_config.DevicesToBind); if(node_config.Security.Enabled) { if(node_config.Security.SelfSignedCertificates) { SecurityPolicy.SetDefaultSecurityPolicy(SecurityPolicy.DefaultEncryptor, SecurityPolicy.DefaultAuthenticator, true); } byte[] blob = null; using(FileStream fs = File.Open(node_config.Security.KeyPath, FileMode.Open)) { blob = new byte[fs.Length]; fs.Read(blob, 0, blob.Length); } RSACryptoServiceProvider rsa_private = new RSACryptoServiceProvider(); rsa_private.ImportCspBlob(blob); CertificateHandler ch = new CertificateHandler(node_config.Security.CertificatePath); bso = new ProtocolSecurityOverlord(current_node, rsa_private, current_node.Rrm, ch); bso.Subscribe(current_node, null); current_node.GetTypeSource(SecurityOverlord.Security).Subscribe(bso, null); current_node.HeartBeatEvent += bso.Heartbeat; if(node_config.Security.TestEnable) { blob = rsa_private.ExportCspBlob(false); RSACryptoServiceProvider rsa_pub = new RSACryptoServiceProvider(); rsa_pub.ImportCspBlob(blob); CertificateMaker cm = new CertificateMaker("United States", "UFL", "ACIS", "David Wolinsky", "*****@*****.**", rsa_pub, "brunet:node:abcdefghijklmnopqrs"); Certificate cacert = cm.Sign(cm, rsa_private); cm = new CertificateMaker("United States", "UFL", "ACIS", "David Wolinsky", "*****@*****.**", rsa_pub, address.ToString()); Certificate cert = cm.Sign(cacert, rsa_private); ch.AddCACertificate(cacert.X509); ch.AddSignedCertificate(cert.X509); } } EdgeListener el = null; foreach(NodeConfig.EdgeListener item in node_config.EdgeListeners) { int port = item.port; if (item.type =="tcp") { try { el = new TcpEdgeListener(port, addresses); } catch { el = new TcpEdgeListener(0, addresses); } } else if (item.type == "udp") { try { el = new UdpEdgeListener(port, addresses); } catch { el = new UdpEdgeListener(0, addresses); } } else if(item.type == "function") { port = port == 0 ? (new Random()).Next(1024, 65535) : port; el = new FunctionEdgeListener(port, 0, null); } else { throw new Exception("Unrecognized transport: " + item.type); } if (node_config.Security.SecureEdgesEnabled) { el = new SecureEdgeListener(el, bso); } current_node.AddEdgeListener(el); } ArrayList RemoteTAs = null; if(node_config.RemoteTAs != null) { RemoteTAs = new ArrayList(); foreach(String ta in node_config.RemoteTAs) { RemoteTAs.Add(TransportAddressFactory.CreateInstance(ta)); } current_node.RemoteTAs = RemoteTAs; } ITunnelOverlap ito = null; ito = new SimpleTunnelOverlap(); el = new Tunnel.TunnelEdgeListener(current_node, ito); if(node_config.Security.SecureEdgesEnabled) { current_node.EdgeVerifyMethod = EdgeVerify.AddressInSubjectAltName; el = new SecureEdgeListener(el, bso); } current_node.AddEdgeListener(el); new TableServer(current_node); if (type == "cache") { _c_dht = new Dht(current_node, 3, 20); _c_dht_proxy = new RpcDhtProxy(_c_dht, current_node); _cs = new CacheList(current_node); //_cll = new ClusterList(current_node); //current_node.MapReduce.SubscribeTask(new MapReduceClusterCache(current_node, _cll)); current_node.MapReduce.SubscribeTask(new MapReduceCache(current_node,_cs)); Console.WriteLine("MapReduceCacheTask is subscribed at {0}", current_node.Address); _c_node = current_node; } else { _q_dht = new Dht(current_node, 3, 20); _q_dht_proxy = new RpcDhtProxy(_c_dht, current_node); CacheList q_cs = new CacheList(current_node); //current_node.MapReduce.SubscribeTask(new MapReduceClusterQuery(current_node, _cll)); current_node.MapReduce.SubscribeTask(new MapReduceQuery(current_node,_cs)); Console.WriteLine("MapReduceQueryTask is subscribed at {0}", current_node.Address); _q_node = current_node; } }
/// <summary>Creates a Brunet.Node, the resulting node will be available in /// the class as _node.</summary> /// <remarks>The steps to creating a node are first constructing it with a /// namespace, optionally adding local ip addresses to bind to, specifying /// local end points, specifying remote end points, and finally registering /// the dht.</remarks> public virtual void CreateNode() { AHAddress address = null; try { address = (AHAddress) AddressParser.Parse(_node_config.NodeAddress); } catch { address = Utils.GenerateAHAddress(); } _node = new StructuredNode(address, _node_config.BrunetNamespace); IEnumerable addresses = IPAddresses.GetIPAddresses(_node_config.DevicesToBind); if(_node_config.Security.Enabled) { if(_node_config.Security.SelfSignedCertificates) { SecurityPolicy.SetDefaultSecurityPolicy(SecurityPolicy.DefaultEncryptor, SecurityPolicy.DefaultAuthenticator, true); } byte[] blob = null; using(FileStream fs = File.Open(_node_config.Security.KeyPath, FileMode.Open)) { blob = new byte[fs.Length]; fs.Read(blob, 0, blob.Length); } RSACryptoServiceProvider rsa_private = new RSACryptoServiceProvider(); rsa_private.ImportCspBlob(blob); CertificateHandler ch = new CertificateHandler(_node_config.Security.CertificatePath); _bso = new ProtocolSecurityOverlord(_node, rsa_private, _node.Rrm, ch); _bso.Subscribe(_node, null); _node.GetTypeSource(SecurityOverlord.Security).Subscribe(_bso, null); _node.HeartBeatEvent += _bso.Heartbeat; if(_node_config.Security.TestEnable) { blob = rsa_private.ExportCspBlob(false); RSACryptoServiceProvider rsa_pub = new RSACryptoServiceProvider(); rsa_pub.ImportCspBlob(blob); CertificateMaker cm = new CertificateMaker("United States", "UFL", "ACIS", "David Wolinsky", "*****@*****.**", rsa_pub, "brunet:node:abcdefghijklmnopqrs"); Certificate cacert = cm.Sign(cm, rsa_private); cm = new CertificateMaker("United States", "UFL", "ACIS", "David Wolinsky", "*****@*****.**", rsa_pub, address.ToString()); Certificate cert = cm.Sign(cacert, rsa_private); ch.AddCACertificate(cacert.X509); ch.AddSignedCertificate(cert.X509); } } EdgeListener el = null; foreach(NodeConfig.EdgeListener item in _node_config.EdgeListeners) { int port = item.port; if(item.type == "tcp") { try { el = new TcpEdgeListener(port, addresses); } catch { el = new TcpEdgeListener(0, addresses); } } else if(item.type == "udp") { try { el = new UdpEdgeListener(port, addresses); } catch { el = new UdpEdgeListener(0, addresses); } } else if(item.type == "function") { port = port == 0 ? (new Random()).Next(1024, 65535) : port; el = new FunctionEdgeListener(port, 0, null); } else { throw new Exception("Unrecognized transport: " + item.type); } if(_node_config.Security.SecureEdgesEnabled) { el = new SecureEdgeListener(el, _bso); } _node.AddEdgeListener(el); } ArrayList RemoteTAs = null; if(_node_config.RemoteTAs != null) { RemoteTAs = new ArrayList(); foreach(String ta in _node_config.RemoteTAs) { RemoteTAs.Add(TransportAddressFactory.CreateInstance(ta)); } _node.RemoteTAs = RemoteTAs; } ITunnelOverlap ito = null; /* if(_node_config.NCService.Enabled) { _ncservice = new NCService(_node, _node_config.NCService.Checkpoint); if (_node_config.NCService.OptimizeShortcuts) { _node.Ssco.TargetSelector = new VivaldiTargetSelector(_node, _ncservice); } ito = new NCTunnelOverlap(_ncservice); } else { ito = new SimpleTunnelOverlap(); } */ el = new Tunnel.TunnelEdgeListener(_node, ito); if(_node_config.Security.SecureEdgesEnabled) { _node.EdgeVerifyMethod = EdgeVerify.AddressInSubjectAltName; el = new SecureEdgeListener(el, _bso); } _node.AddEdgeListener(el); new TableServer(_node); _dht = new Dht(_node, 3, 20); _dht_proxy = new RpcDhtProxy(_dht, _node); }
/// <summary> /// Rest POST. /// </summary> /// <param name="query">Finalized Endpoint Query with parameters.</param> /// <param name="headers">Optional header information for the request.</param> /// <param name="timeout">Optional time in seconds before request expires.</param> /// <param name="readResponseData">Optional bool. If its true, response data will be read from web request download handler.</param> /// <param name="certificateHandler">Optional certificate handler for custom certificate verification</param> /// <param name="disposeCertificateHandlerOnDispose">Optional bool. If true and <paramref name="certificateHandler"/> is not null, <paramref name="certificateHandler"/> will be disposed, when the underlying UnityWebRequest is disposed.</param> /// <returns>The response data.</returns> public static async Task <Response> PostAsync(string query, Dictionary <string, string> headers = null, int timeout = -1, bool readResponseData = false, CertificateHandler certificateHandler = null, bool disposeCertificateHandlerOnDispose = true) { using (var webRequest = UnityWebRequest.Post(query, null as string)) { return(await ProcessRequestAsync(webRequest, timeout, headers, readResponseData, certificateHandler, disposeCertificateHandlerOnDispose)); } }
public SecurityOverlord(RSACryptoServiceProvider rsa, ReqrepManager rrman, CertificateHandler ch) { _private_key = rsa; _private_key_lock = new object(); _ch = ch; _spi = new Dictionary<int, Dictionary<ISender, SecurityAssociation>>(); _cookie = new byte[CookieLength]; _rand = new Random(); _rand.NextBytes(_cookie); _rrman = rrman; _last_heartbeat = DateTime.UtcNow; _rrman.Subscribe(this, null); }
/// <summary>Creates an ApplicationNode and prepares it for connection to /// the overlay. For historical reasons it is linked to _node, _dht, /// _rpc_dht, and _bso.</summary> public virtual ApplicationNode CreateNode(NodeConfig node_config) { // Get a Node ID for the new Node AHAddress address = null; try { address = (AHAddress) AddressParser.Parse(node_config.NodeAddress); } catch { address = Utils.GenerateAHAddress(); } // Create the Node state StructuredNode node = new StructuredNode(address, node_config.BrunetNamespace); _shutdown.OnExit += node.Disconnect; IEnumerable addresses = IPAddresses.GetIPAddresses(node_config.DevicesToBind); SecurityOverlord so = null; // Enable Security if requested if(node_config.Security.Enabled) { if(node_config.Security.SelfSignedCertificates) { SecurityPolicy.SetDefaultSecurityPolicy(SecurityPolicy.DefaultEncryptor, SecurityPolicy.DefaultAuthenticator, true); } byte[] blob = null; using(FileStream fs = File.Open(node_config.Security.KeyPath, FileMode.Open)) { blob = new byte[fs.Length]; fs.Read(blob, 0, blob.Length); } RSACryptoServiceProvider rsa_private = new RSACryptoServiceProvider(); rsa_private.ImportCspBlob(blob); CertificateHandler ch = null; if(node_config.Security.Dtls) { ch = new OpenSslCertificateHandler(node_config.Security.CertificatePath, address.ToString()); } else { ch = new CertificateHandler(node_config.Security.CertificatePath, address.ToString()); } if(node_config.Security.SecureEdges) { node.EdgeVerifyMethod = EdgeVerify.AddressInSubjectAltName; } // A hack to enable a test for security that doesn't require each peer // to exchange certificates if(node_config.Security.TestEnable) { blob = rsa_private.ExportCspBlob(false); RSACryptoServiceProvider rsa_pub = new RSACryptoServiceProvider(); rsa_pub.ImportCspBlob(blob); CertificateMaker cm = new CertificateMaker("United States", "UFL", "ACIS", "David Wolinsky", "*****@*****.**", rsa_pub, "brunet:node:abcdefghijklmnopqrs"); Certificate cacert = cm.Sign(cm, rsa_private); cm = new CertificateMaker("United States", "UFL", "ACIS", "David Wolinsky", "*****@*****.**", rsa_pub, address.ToString()); Certificate cert = cm.Sign(cacert, rsa_private); ch.AddCACertificate(cacert.X509); ch.AddSignedCertificate(cert.X509); } if(node_config.Security.Dtls) { OpenSslCertificateHandler ssl_ch = ch as OpenSslCertificateHandler; so = new DtlsOverlord(rsa_private, ssl_ch, new PType(20)); node.GetTypeSource(new PType(20)).Subscribe(so, null); } else { so = new SymphonySecurityOverlord(node, rsa_private, ch, node.Rrm); node.GetTypeSource(PeerSecOverlord.Security).Subscribe(so, null); } so.Subscribe(node, null); } // Add Dht new TableServer(node); IDht dht = new Dht(node, 3, 20); RpcDhtProxy dht_proxy = new RpcDhtProxy(dht, node); // Setup Vivaldi if requested IRelayOverlap ito = null; NCService ncservice = null; if(node_config.NCService.Enabled) { ncservice = new NCService(node, node_config.NCService.Checkpoint); if (node_config.NCService.OptimizeShortcuts) { node.Ssco.TargetSelector = new VivaldiTargetSelector(node, ncservice); } ito = new NCRelayOverlap(ncservice); } else { ito = new SimpleRelayOverlap(); } // Create the ApplicationNode ApplicationNode app_node = new ApplicationNode(node, dht, dht_proxy, ncservice, so); // Add Edge listeners EdgeListener el = null; foreach(NodeConfig.EdgeListener item in node_config.EdgeListeners) { el = CreateEdgeListener(item, app_node, addresses); if(node_config.Security.SecureEdgesEnabled) { el = new SecureEdgeListener(el, so); } node.AddEdgeListener(el); } // Create the tunnel and potentially wrap it in a SecureEL el = new Relay.RelayEdgeListener(node, ito); if(node_config.Security.SecureEdgesEnabled) { el = new SecureEdgeListener(el, so); } node.AddEdgeListener(el); List<TransportAddress> RemoteTAs = null; if(node_config.RemoteTAs != null) { RemoteTAs = new List<TransportAddress>(); foreach(String ta in node_config.RemoteTAs) { RemoteTAs.Add(TransportAddressFactory.CreateInstance(ta)); } node.RemoteTAs = RemoteTAs; } // Add XmlRpc if(node_config.XmlRpcManager.Enabled) { if(_xrm == null) { _xrm = new XmlRpcManagerServer(node_config.XmlRpcManager.Port); } _xrm.Add(node, GetXmlRpcUri(app_node)); new RpcDht(dht, node); } if(node_config.PrivateNodeConfig != null && node_config.PrivateNodeConfig.Enabled) { CreatePrivateNode(app_node, NodeConfig.GetPrivateNodeConfig(node_config)); } return app_node; }
public void AddBadLocalCert() { CertificateHandler ch = new CertificateHandler("certs", "12345"); RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(512); byte[] blob = rsa.ExportCspBlob(false); RSACryptoServiceProvider rsa_pub = new RSACryptoServiceProvider(); rsa_pub.ImportCspBlob(blob); string ID = "brunet:node:PXYSWDL5SZDHDDXJKZCLFENOP2KZDMBU"; CertificateMaker cm = new CertificateMaker("US", "UFL", "ACIS", "David Wolinsky", "*****@*****.**", rsa_pub, ID); Certificate cert_0 = cm.Sign(cm, rsa); ch.AddCACertificate(cert_0.X509); try { ch.AddSignedCertificate(cert_0.X509); Assert.IsTrue(false, "Shouldn't add this certificate!"); } catch { } CertificateMaker cm0 = new CertificateMaker("US", "UFL", "ACIS", "David Wolinsky", "*****@*****.**", rsa_pub, "12345"); Certificate cert_1 = cm0.Sign(cm, rsa); ch.AddSignedCertificate(cert_1.X509); }
protected virtual StructuredNode PrepareNode(int id, AHAddress address) { if (TakenIDs.ContainsKey(id)) { throw new Exception("ID already taken"); } StructuredNode node = new StructuredNode(address, BrunetNamespace); NodeMapping nm = new NodeMapping(); nm.ID = id; TakenIDs[id] = nm; nm.Node = node; Nodes.Add((Address)address, nm); EdgeListener el = CreateEdgeListener(nm.ID); if (_secure_edges || _secure_senders) { byte[] blob = _se_key.ExportCspBlob(true); RSACryptoServiceProvider rsa_copy = new RSACryptoServiceProvider(); rsa_copy.ImportCspBlob(blob); string username = address.ToString().Replace('=', '0'); CertificateMaker cm = new CertificateMaker("United States", "UFL", "ACIS", username, "*****@*****.**", rsa_copy, address.ToString()); Certificate cert = cm.Sign(_ca_cert, _se_key); CertificateHandler ch = null; if (_dtls) { ch = new OpenSslCertificateHandler(); } else { ch = new CertificateHandler(); } ch.AddCACertificate(_ca_cert.X509); ch.AddSignedCertificate(cert.X509); if (_dtls) { nm.SO = new DtlsOverlord(rsa_copy, ch, PeerSecOverlord.Security); } else { nm.Sso = new SymphonySecurityOverlord(node, rsa_copy, ch, node.Rrm); nm.SO = nm.Sso; } var brh = new BroadcastRevocationHandler(_ca_cert, nm.SO); node.GetTypeSource(BroadcastRevocationHandler.PType).Subscribe(brh, null); ch.AddCertificateVerification(brh); nm.SO.Subscribe(node, null); node.GetTypeSource(PeerSecOverlord.Security).Subscribe(nm.SO, null); } if (_pathing) { nm.PathEM = new PathELManager(el, nm.Node); nm.PathEM.Start(); el = nm.PathEM.CreatePath(); PType path_p = PType.Protocol.Pathing; nm.Node.DemuxHandler.GetTypeSource(path_p).Subscribe(nm.PathEM, path_p); } if (_secure_edges) { node.EdgeVerifyMethod = EdgeVerify.AddressInSubjectAltName; el = new SecureEdgeListener(el, nm.SO); } node.AddEdgeListener(el); if (!_start) { node.RemoteTAs = GetRemoteTAs(); } IRelayOverlap ito = null; if (NCEnable) { nm.NCService = new NCService(node, new Point()); // My evaluations show that when this is enabled the system sucks // (node as StructuredNode).Sco.TargetSelector = new VivaldiTargetSelector(node, ncservice); ito = new NCRelayOverlap(nm.NCService); } else { ito = new SimpleRelayOverlap(); } if (_broken != 0) { el = new Relay.RelayEdgeListener(node, ito); if (_secure_edges) { el = new SecureEdgeListener(el, nm.SO); } node.AddEdgeListener(el); } BroadcastHandler bhandler = new BroadcastHandler(node as StructuredNode); node.DemuxHandler.GetTypeSource(BroadcastSender.PType).Subscribe(bhandler, null); node.DemuxHandler.GetTypeSource(SimBroadcastPType).Subscribe(SimBroadcastHandler, null); // Enables Dht data store new TableServer(node); nm.Dht = new Dht(node, 3, 20); nm.DhtProxy = new RpcDhtProxy(nm.Dht, node); return(node); }
static void Main(string[] args) { AppDomain.CurrentDomain.AssemblyResolve += Resolver; Init(); if (!IsAnAdministrator()) { Console.ForegroundColor = ConsoleColor.Red; Console.Write("Error: "); Console.ResetColor(); Console.Write("Servant needs to run as administrator to access IIS."); Console.WriteLine(); Console.ForegroundColor = ConsoleColor.DarkYellow; Console.Write("Solution: "); Console.ResetColor(); Console.Write("Right click Servant.Server.exe and select 'Run as administrator'."); Console.WriteLine(); Console.WriteLine(); Console.WriteLine("Press any key to exit..."); Console.ReadKey(); return; } if (!IsIisInstalled()) { Console.ForegroundColor = ConsoleColor.Red; Console.Write("Error: "); Console.ResetColor(); Console.Write("IIS needs to be installed to use Servant."); Console.WriteLine(); Console.WriteLine("Press any key to exit..."); Console.ReadKey(); return; } var command = args.FirstOrDefault() ?? ""; Configuration = TinyIoCContainer.Current.Resolve <ServantConfiguration>(); if (Configuration.IsHttps()) { if (!IsServantCertificateInstalled()) { InstallServantCertificate(); } var servantPort = new Uri(Configuration.ServantUrl).Port; if (!CertificateHandler.IsCertificateBound(servantPort)) { CertificateHandler.AddCertificateBinding(servantPort); } } switch (command) { case "install": if (IsAlreadyInstalled()) { Console.WriteLine("Servant is already installed. Use /uninstall to uninstall."); Console.ReadLine(); return; } const string servantServiceName = "Servant for IIS"; var existingServantService = ServiceController.GetServices().FirstOrDefault(s => s.ServiceName == servantServiceName); if (existingServantService != null) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Servant is already running on this machine."); Console.ReadLine(); return; } ManagedInstallerClass.InstallHelper(new[] { "/LogToConsole=false", Assembly.GetExecutingAssembly().Location }); var startController = new ServiceController("Servant for IIS"); startController.Start(); StartBrowser(); Console.WriteLine("Servant was successfully installed. Please complete the installation from your browser on " + Configuration.ServantUrl); break; case "uninstall": Console.WriteLine(); Console.WriteLine("Trying to uninstall the Servant service..."); try { ManagedInstallerClass.InstallHelper(new[] { "/u", "/LogToConsole=false", Assembly.GetExecutingAssembly().Location }); Console.WriteLine("The service was successfully uninstalled."); } catch (Exception) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("An error occurred while trying to uninstall Servant."); Console.ResetColor(); } break; default: if (Environment.UserInteractive || (args != null && args.Length > 0)) { Console.WriteLine(); Console.WriteLine("Welcome to Servant for IIS."); Console.WriteLine(); StartServant(); Console.WriteLine("You can now manage your server from " + Configuration.ServantUrl); StartBrowser(); while (true) { Console.ReadLine(); } } ServiceBase.Run(new ServantService()); break; } }
public void FindCertificateTest() { CertificateHandler ch = new CertificateHandler(); RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(512); byte[] blob = rsa.ExportCspBlob(false); RSACryptoServiceProvider rsa_pub = new RSACryptoServiceProvider(); rsa_pub.ImportCspBlob(blob); List<MemBlock> supported = new List<MemBlock>(); List<MemBlock> unsupported = new List<MemBlock>(); for(int i = 0; i < 20; i++) { CertificateMaker cm = new CertificateMaker("US", "UFL", "ACIS", "David Wolinsky", "*****@*****.**" + i, rsa_pub, i.ToString()); Certificate cert = cm.Sign(cm, rsa); if(i % 2 == 0) { ch.AddCACertificate(cert.X509); ch.AddSignedCertificate(cert.X509); supported.Add(cert.SerialNumber); } else { unsupported.Add(cert.SerialNumber); } } Assert.IsNotNull(ch.FindCertificate(supported), "Should find a certificate"); bool success = false; try { success = ch.FindCertificate(unsupported) != null; } catch { } Assert.IsTrue(!success, "Should not find a certificate"); List<MemBlock> mixed = new List<MemBlock>(unsupported); mixed.Insert(4 ,supported[1]); Assert.AreEqual(supported[1], MemBlock.Reference(ch.FindCertificate(mixed).SerialNumber), "Only one supported"); }
public void Test() { CertificateHandler ch = new CertificateHandler(); ch.AddCACertificate(_ca_cert.X509); ch.AddCertificateVerification(this); ArrayList revoked_users = new ArrayList(); revoked_users.Add("joker"); revoked_users.Add("bad_guy"); revoked_users.Add("adversary"); revoked_users.Add("noobs"); // create revocation list byte[] to_sign = null; using(MemoryStream ms = new MemoryStream()) { NumberSerializer.WriteLong(DateTime.UtcNow.Ticks, ms); AdrConverter.Serialize(revoked_users, ms); to_sign = ms.ToArray(); } // sign revocation list SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider(); byte[] hash = sha1.ComputeHash(to_sign); byte[] signature = _private_key.SignHash(hash, CryptoConfig.MapNameToOID("SHA1")); byte[] data = new byte[4 + to_sign.Length + signature.Length]; NumberSerializer.WriteInt(to_sign.Length, data, 0); to_sign.CopyTo(data, 4); signature.CopyTo(data, 4 + to_sign.Length); UpdateRl(data); X509Certificate likable_guy = CreateCert("likable_guy"); X509Certificate joker = CreateCert("joker"); X509Certificate bad_guy = CreateCert("bad_guy"); X509Certificate good_guy = CreateCert("good_guy"); X509Certificate adversary = CreateCert("adversary"); X509Certificate noobs = CreateCert("noobs"); X509Certificate friendly_guy = CreateCert("friendly_guy"); Assert.IsTrue(ch.Verify(likable_guy, _remote_id), "Likable guy"); bool success = false; try { success = ch.Verify(adversary, _remote_id); } catch { } Assert.AreEqual(success, false, "adversary"); try { success = ch.Verify(joker, _remote_id); } catch { } Assert.AreEqual(success, false, "joker"); Assert.IsTrue(ch.Verify(friendly_guy, _remote_id), "friendly guy"); try { success = ch.Verify(noobs, _remote_id); } catch { } Assert.AreEqual(success, false, "noobs"); try { success = ch.Verify(bad_guy, _remote_id); } catch { } Assert.AreEqual(success, false, "bad_guy"); Assert.IsTrue(ch.Verify(good_guy, _remote_id), "good guy"); }
public void Test() { CertificateHandler ch = new CertificateHandler(); ch.AddCACertificate(_ca_cert.X509); ch.AddCertificateVerification(this); ArrayList revoked_users = new ArrayList(); revoked_users.Add("joker"); revoked_users.Add("bad_guy"); revoked_users.Add("adversary"); revoked_users.Add("noobs"); // create revocation list byte[] to_sign = null; using (MemoryStream ms = new MemoryStream()) { NumberSerializer.WriteLong(DateTime.UtcNow.Ticks, ms); AdrConverter.Serialize(revoked_users, ms); to_sign = ms.ToArray(); } // sign revocation list SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider(); byte[] hash = sha1.ComputeHash(to_sign); byte[] signature = _private_key.SignHash(hash, CryptoConfig.MapNameToOID("SHA1")); byte[] data = new byte[4 + to_sign.Length + signature.Length]; NumberSerializer.WriteInt(to_sign.Length, data, 0); to_sign.CopyTo(data, 4); signature.CopyTo(data, 4 + to_sign.Length); UpdateRl(data); X509Certificate likable_guy = CreateCert("likable_guy"); X509Certificate joker = CreateCert("joker"); X509Certificate bad_guy = CreateCert("bad_guy"); X509Certificate good_guy = CreateCert("good_guy"); X509Certificate adversary = CreateCert("adversary"); X509Certificate noobs = CreateCert("noobs"); X509Certificate friendly_guy = CreateCert("friendly_guy"); Assert.IsTrue(ch.Verify(likable_guy, null, _remote_id), "Likable guy"); bool success = false; try { success = ch.Verify(adversary, null, _remote_id); } catch { } Assert.AreEqual(success, false, "adversary"); try { success = ch.Verify(joker, null, _remote_id); } catch { } Assert.AreEqual(success, false, "joker"); Assert.IsTrue(ch.Verify(friendly_guy, null, _remote_id), "friendly guy"); try { success = ch.Verify(noobs, null, _remote_id); } catch { } Assert.AreEqual(success, false, "noobs"); try { success = ch.Verify(bad_guy, null, _remote_id); } catch { } Assert.AreEqual(success, false, "bad_guy"); Assert.IsTrue(ch.Verify(good_guy, null, _remote_id), "good guy"); }
protected SecurityOverlord CreateInvalidSO(string name, int level) { if(rsa == null) { rsa = new RSACryptoServiceProvider(); byte[] blob = rsa.ExportCspBlob(false); RSACryptoServiceProvider rsa_pub = new RSACryptoServiceProvider(); rsa_pub.ImportCspBlob(blob); CertificateMaker cm = new CertificateMaker("United States", "UFL", "ACIS", "David Wolinsky", "*****@*****.**", rsa_pub, "brunet:node:abcdefghijklmnopqrs"); Certificate cert = cm.Sign(cm, rsa); x509 = cert.X509; } CertificateHandler ch = new CertificateHandler(); if(level == 2 || level == 0) { ch.AddCACertificate(x509); } if(level == 3 || level == 0) { ch.AddSignedCertificate(x509); } ReqrepManager rrm = new ReqrepManager("so" + name); _timeout += rrm.TimeoutChecker; SecurityOverlord so = new SecurityOverlord(rsa_safe, rrm, ch); so.AnnounceSA += AnnounceSA; RoutingDataHandler rdh = new RoutingDataHandler(); rrm.Subscribe(so, null); so.Subscribe(rdh, null); rdh.Subscribe(rrm, null); return so; }