static void Main(string[] args) { using (TikSession session = new TikSession(TikConnectorType.Api)) { //REMARS - works without access to mikrotik router FirewallMangleList dest = CreateList(); FirewallMangleList srcTmp = CreateList(); List <FirewallMangle> src = new List <FirewallMangle>(srcTmp); FirewallMangle additionalMangle = new FirewallMangle() { SrcAddress = "192.168.1.4", Action = "allow" }; src.Insert(0, additionalMangle); dest.MergeSubset(dest, src, dest.First(), m => m.SrcAddress, (d, s) => d.Action = s.Action); foreach (FirewallMangle mangle in dest) { Console.WriteLine(mangle); } Console.WriteLine("I/U/D/M {0}/{1}/{2}/{3}", dest.NewCount, dest.UpdatedCount, dest.DeletedCount, dest.MovesCount); Console.ReadLine(); } }
public static Task <IEnumerable <IPAddress> > ReadPublicIpv4AddressesFromMikrotikRouter(Config config) { return(Task.Run(() => { Log.Trace("Reading public IPv4 addresses from Mikrotik Router ({0})...", config.routerAddress); using (var session = new TikSession(TikConnectorType.Api)) { var password = UnprotectSecret(config.routerPassword, config.randomString); session.Open(config.routerAddress, config.routerUser, password); Log.Trace("Connected to router OK."); var conn = (Tik4Net.Connector.Api.IApiConnector)session.Connector; var result = new List <IPAddress>(); foreach (var iface in config.routerPublicInterfaces) { var publicIp = conn.ApiExecuteReader("/ip/address/print\n?interface=" + iface).FirstOrDefault(); if (publicIp == null) { Log.Warn("Unable to find interface in router: " + iface); continue; } var ipAndMask = publicIp.GetStringValueOrNull("address", true); var ip = ipAndMask.Substring(0, ipAndMask.LastIndexOf('/')); Log.Debug("Read public IPv4 address '{0}' from Mikrotik Router OK.", ip); result.Add(IPAddress.Parse(ip)); } return result.AsEnumerable(); } })); }
private void btnConsoleClose_Click(object sender, EventArgs e) { if (consoleSession != null) { consoleSession.Dispose(); consoleSession = null; } }
static void Main(string[] args) { using (TikSession session = new TikSession(TikConnectorType.Api)) { session.Open(HOST, USER, PASS); SystemResource resource = SystemResource.LoadInstance(); Console.WriteLine("Mikrotik version: {0}", resource.Version); } Console.ReadLine(); }
internal TikPropertyParser(TikSession session, string request, List <string> responseDataRows) { Guard.ArgumentNotNull(responseDataRows, "responseDataRows"); Guard.ArgumentNotNullOrEmptyString(request, "request"); //entityPath string[] items = request.Split('\n'); if (items[0].Contains(@"/print")) //remove /print sufix if present { this.entityPath = items[0].Substring(0, items[0].IndexOf(@"/print")); } else { this.entityPath = items[0]; } StringHelper.GetEntityFqn(entityPath, out entityNamespace, out entityName); //response -> properties props = new Dictionary <string, FieldType>(); entityExampleRow = ""; foreach (string responseDataRow in responseDataRows) { if (responseDataRow.StartsWith("!re")) { if (string.IsNullOrEmpty(entityExampleRow)) { entityExampleRow = responseDataRow; } ITikEntityRow row = session.Connector.CreateEntityRow(responseDataRow); foreach (string key in row.Keys) { bool nullable = StringHelper.DetermineFieldNulable(key); FieldType fieldType = StringHelper.DetermineFieldTypeFromValue(row.GetStringValueOrNull(key, true), nullable); if (!props.ContainsKey(key)) { props.Add(key, fieldType); } else { FieldType actualType = props[key]; if (actualType != fieldType) //set type=string if there more than one variant { props[key] = nullable ? FieldType.StringNulable : FieldType.String; } } } } } }
private void btnConsoleOpen_Click(object sender, EventArgs e) { if (consoleSession != null) { throw new Exception("Console session is already active."); } else { consoleSession = new TikSession(TikConnectorType.Api); consoleSession.Open(tbHost.Text, int.Parse(tbPort.Text), tbUser.Text, tbPassword.Text); } }
static void Main(string[] args) { using (TikSession session = new TikSession(TikConnectorType.Api)) { session.Open(HOST, USER, PASS); Tik4Net.Objects.System.SystemResource resource = Tik4Net.Objects.System.SystemResource.LoadInstance(); IApiConnector apiConnector = (IApiConnector)session.Connector; //ip-scan example List <ITikEntityRow> ipScanList = apiConnector.ApiExecuteReader("/tool/ip-scan", new Dictionary <string, string> { { "address-range", "192.168.0.0/16" }, { "interface", "ether1" }, { "duration", "120" } }); foreach (ITikEntityRow row in ipScanList) { Console.WriteLine("Address: {0}, MAC: {1}, DNS: {2}", row.GetStringValueOrNull("address", true), row.GetStringValueOrNull("mac-address", false), row.GetStringValueOrNull("dns", false)); } //mac-scan sample List <ITikEntityRow> macScanList = apiConnector.ApiExecuteReader("/tool/mac-scan", new Dictionary <string, string> { { "interface", "ether1" }, { "duration", "120" } }); foreach (ITikEntityRow row in macScanList) { Console.WriteLine("Address: {0}, MAC: {1}", row.GetStringValueOrNull("address", true), row.GetStringValueOrNull("mac-address", true)); } //logging example apiConnector.Log("Test", Tik4Net.Objects.LogLevel.Info); //REMARKS - you should use LogList.LogDebug for this case. //execute scalar - select for single value string result = apiConnector.ApiExecuteScalar("/ip/firewall/connection/print", new Dictionary <string, string> { { "count-only", "" } }); Console.WriteLine(result); } }
static void Main(string[] args) { using (TikSession session = new TikSession(TikConnectorType.Api)) { session.Open(HOST, USER, PASS); Tik4Net.Objects.System.SystemResource resource = Tik4Net.Objects.System.SystemResource.LoadInstance(); IApiConnector apiConnector = (IApiConnector)session.Connector; //ip-scan example List<ITikEntityRow> ipScanList = apiConnector.ApiExecuteReader("/tool/ip-scan", new Dictionary<string, string> { {"address-range", "192.168.0.0/16"}, {"interface", "ether1"}, {"duration", "120" } }); foreach (ITikEntityRow row in ipScanList) { Console.WriteLine("Address: {0}, MAC: {1}, DNS: {2}", row.GetStringValueOrNull("address", true), row.GetStringValueOrNull("mac-address", false), row.GetStringValueOrNull("dns", false)); } //mac-scan sample List<ITikEntityRow> macScanList = apiConnector.ApiExecuteReader("/tool/mac-scan", new Dictionary<string, string> { {"interface", "ether1" }, {"duration", "120" } }); foreach (ITikEntityRow row in macScanList) { Console.WriteLine("Address: {0}, MAC: {1}", row.GetStringValueOrNull("address", true), row.GetStringValueOrNull("mac-address", true)); } //logging example apiConnector.Log("Test", Tik4Net.Objects.LogLevel.Info); //REMARKS - you should use LogList.LogDebug for this case. //execute scalar - select for single value string result = apiConnector.ApiExecuteScalar("/ip/firewall/connection/print", new Dictionary<string,string>{{"count-only", ""}}); Console.WriteLine(result); } }
internal TikPropertyParser(TikSession session, string request, List<string> responseDataRows) { Guard.ArgumentNotNull(responseDataRows, "responseDataRows"); Guard.ArgumentNotNullOrEmptyString(request, "request"); //entityPath string[] items = request.Split('\n'); if (items[0].Contains(@"/print")) //remove /print sufix if present this.entityPath = items[0].Substring(0, items[0].IndexOf(@"/print")); else this.entityPath = items[0]; StringHelper.GetEntityFqn(entityPath, out entityNamespace, out entityName); //response -> properties props = new Dictionary<string, FieldType>(); entityExampleRow = ""; foreach (string responseDataRow in responseDataRows) { if (responseDataRow.StartsWith("!re")) { if (string.IsNullOrEmpty(entityExampleRow)) entityExampleRow = responseDataRow; ITikEntityRow row = session.Connector.CreateEntityRow(responseDataRow); foreach (string key in row.Keys) { bool nullable = StringHelper.DetermineFieldNulable(key); FieldType fieldType = StringHelper.DetermineFieldTypeFromValue(row.GetStringValueOrNull(key, true), nullable); if (!props.ContainsKey(key)) props.Add(key, fieldType); else { FieldType actualType = props[key]; if (actualType != fieldType) //set type=string if there more than one variant props[key] = nullable ? FieldType.StringNulable : FieldType.String; } } } } }
private void loginButton_Click(object sender, EventArgs e) { //get instanct of TikSession TikSession ts = PubConst.tikSession; try { //Connect to router ts.Open(ConnectToTextBox.Text, loginTextBox.Text, passwordTextBox.Text); } catch (Exception ex) { // working on exception MessageBox.Show("Login failed!" + ex.Message); return; } // hide self & show mainform MainForm mf = new MainForm(); this.Hide(); mf.Show(); }
/// <summary> /// Initializes a new instance of the <see cref="InterfaceList"/> class. /// </summary> /// <param name="session">The session used to access mikrotik.</param> public InterfaceList(TikSession session) : base(session) { }
/// <summary> /// Initializes a new instance of the <see cref="IpAddressList"/> class. /// </summary> /// <param name="session">The session used to access mikrotik.</param> public IpAddressList(TikSession session) : base(session) { }
static void Main(string[] args) { using (TikSession session = new TikSession(TikConnectorType.Api)) { session.Open(HOST, USER, PASS); //load potential login errors LogList logItems = new LogList(); logItems.LoadByTopics("system,error,critical"); //load actual addresslist FirewallAddressListList addrListItems = new FirewallAddressListList(); addrListItems.LoadByList(DROP_ADDR_LIST); //Find all logon erros (possible atack) Dictionary<string, Dictionary<string, int>> atacksPerIp = new Dictionary<string, Dictionary<string, int>>(); //<ip, <user, cnt>> foreach (Log log in logItems) { Match match = loginErrorRegex.Match(log.Message); if (match.Success) //is logon error format { string atackerIp = match.Groups["IP"].Value; string atackerTechnology = match.Groups["CONN"].Value; string atackerLogin = match.Groups["USER"].Value; if (!atackerIp.StartsWith(IP_PREFIX_WHITELIST, StringComparison.OrdinalIgnoreCase)) //IP is not in white-list { if (checkedTechnology.Contains(atackerTechnology, StringComparer.OrdinalIgnoreCase)) //technology is in checked list (should be handled) { if (!atacksPerIp.ContainsKey(atackerIp)) atacksPerIp.Add(atackerIp, new Dictionary<string, int>()); if (!atacksPerIp[atackerIp].ContainsKey(atackerLogin)) atacksPerIp[atackerIp].Add(atackerLogin, 0); atacksPerIp[atackerIp][atackerLogin] = atacksPerIp[atackerIp][atackerLogin] + 1; } } } //Disable all atackers foreach (KeyValuePair<string, Dictionary<string, int>> atackFromIp in atacksPerIp) { if (atackFromIp.Value.Keys.Any(login => LOGIN_BLACKLIST.Contains(login)) //in blacklist || atackFromIp.Value.Keys.Count >= CNT_OF_LOGINS_PER_IP_LIMIT || atackFromIp.Value.Any(p=>p.Value >= CNT_OF_ERRORS_PER_LOGIN_LIMIT)) { //should be disabled if (!addrListItems.Any(i => i.Address == atackFromIp.Key)) { //not already in disabled list addrListItems.Add(new FirewallAddressList() { Address = atackFromIp.Key, Disabled = false, List = DROP_ADDR_LIST }); } } } if (addrListItems.IsModified) addrListItems.Save(); } } }
}; //if user name is in blacklist, than previous two lines limit is treated as 1 static void Main(string[] args) { using (TikSession session = new TikSession(TikConnectorType.Api)) { session.Open(HOST, USER, PASS); //load potential login errors LogList logItems = new LogList(); logItems.LoadByTopics("system,error,critical"); //load actual addresslist FirewallAddressListList addrListItems = new FirewallAddressListList(); addrListItems.LoadByList(DROP_ADDR_LIST); //Find all logon erros (possible atack) Dictionary <string, Dictionary <string, int> > atacksPerIp = new Dictionary <string, Dictionary <string, int> >(); //<ip, <user, cnt>> foreach (Log log in logItems) { Match match = loginErrorRegex.Match(log.Message); if (match.Success) //is logon error format { string atackerIp = match.Groups["IP"].Value; string atackerTechnology = match.Groups["CONN"].Value; string atackerLogin = match.Groups["USER"].Value; if (!atackerIp.StartsWith(IP_PREFIX_WHITELIST, StringComparison.OrdinalIgnoreCase)) //IP is not in white-list { if (checkedTechnology.Contains(atackerTechnology, StringComparer.OrdinalIgnoreCase)) //technology is in checked list (should be handled) { if (!atacksPerIp.ContainsKey(atackerIp)) { atacksPerIp.Add(atackerIp, new Dictionary <string, int>()); } if (!atacksPerIp[atackerIp].ContainsKey(atackerLogin)) { atacksPerIp[atackerIp].Add(atackerLogin, 0); } atacksPerIp[atackerIp][atackerLogin] = atacksPerIp[atackerIp][atackerLogin] + 1; } } } //Disable all atackers foreach (KeyValuePair <string, Dictionary <string, int> > atackFromIp in atacksPerIp) { if (atackFromIp.Value.Keys.Any(login => LOGIN_BLACKLIST.Contains(login)) || //in blacklist atackFromIp.Value.Keys.Count >= CNT_OF_LOGINS_PER_IP_LIMIT || atackFromIp.Value.Any(p => p.Value >= CNT_OF_ERRORS_PER_LOGIN_LIMIT)) { //should be disabled if (!addrListItems.Any(i => i.Address == atackFromIp.Key)) { //not already in disabled list addrListItems.Add(new FirewallAddressList() { Address = atackFromIp.Key, Disabled = false, List = DROP_ADDR_LIST }); } } } if (addrListItems.IsModified) { addrListItems.Save(); } } } }
/// <summary> /// Initializes a new instance of the <see cref="QueueSimpleList"/> class. /// </summary> /// <param name="session">The session used to access mikrotik.</param> public QueueSimpleList(TikSession session) : base(session) { }
/// <summary> /// Initializes a new instance of the <see cref="LogList"/> class. /// </summary> /// <param name="session">The session used to access mikrotik.</param> public LogList(TikSession session) : base(session) { }
/// <summary> /// Initializes a new instance of the <see cref="SystemResourceList"/> class. /// </summary> /// <param name="session">The session used to access mikrotik.</param> public SystemResourceList(TikSession session) : base(session) { }
/// <summary> /// Initializes a new instance of the <see cref="FirewallMangleList"/> class. /// </summary> /// <param name="session">The session used to access mikrotik.</param> public FirewallMangleList(TikSession session) : base(session) { }
private void btnConsoleOpen_Click(object sender, EventArgs e) { if (consoleSession != null) throw new Exception("Console session is already active."); else { consoleSession = new TikSession(TikConnectorType.Api); consoleSession.Open(tbHost.Text, int.Parse(tbPort.Text), tbUser.Text, tbPassword.Text); } }
private void Form1_FormClosed(object sender, FormClosedEventArgs e) { if (consoleSession != null) { consoleSession.Dispose(); consoleSession = null; } }
/// <summary> /// Initializes a new instance of the <see cref="InterfaceEthernetList"/> class. /// </summary> /// <param name="session">The session used to access mikrotik.</param> public InterfaceEthernetList(TikSession session) : base(session) { }
/// <summary> /// Initializes a new instance of the <see cref="InterfaceWirelessList"/> class. /// </summary> /// <param name="session">The session used to access mikrotik.</param> public InterfaceWirelessList(TikSession session) : base(session) { }
/// <summary> /// Initializes a new instance of the <see cref="FirewallNatList"/> class. /// </summary> /// <param name="session">The session used to access mikrotik.</param> public FirewallNatList(TikSession session) : base(session) { }
/// <summary> /// See <see cref="ILogConnector.Log"/> for details. /// </summary> public static void LogWarning(string message) { TikSession.CastActiveConnector <ILogConnector>().Log(message, LogLevel.Warning); }
/// <summary> /// Initializes a new instance of the <see cref="FirewallFilterList"/> class. /// </summary> /// <param name="session">The session used to access mikrotik.</param> public FirewallFilterList(TikSession session) : base(session) { }
/// <summary> /// See <see cref="ILogConnector.Log"/> for details. /// </summary> public static void LogError(string message) { TikSession.CastActiveConnector <ILogConnector>().Log(message, LogLevel.Error); }
/// <summary> /// Initializes a new instance of the <see cref="FirewallAddressListList"/> class. /// </summary> /// <param name="session">The session used to access mikrotik.</param> public FirewallAddressListList(TikSession session) : base(session) { }
/// <summary> /// Initializes a new instance of the <see cref="QueueTypeList"/> class. /// </summary> /// <param name="session">The session used to access mikrotik.</param> public QueueTypeList(TikSession session) : base(session) { }