DigitalSignage – Free Video Slideshow – FFMPEG – Batch Script to Export JPG or PNG to MP4

The goal: take 100 .JPG or .PNG images, and export them to a video-slideshow as a MP4 container on a Windows computer.

This was way harder than I expected it to be without spending $60-100 on complex video editing software.  So many of the conversion guides require Linux or OSX to use the Blob (wildcard) feature for inputting file-names, but it doesn’t work on Windows.

I needed something simple enough I could give it to a common user, and get them creating video slideshows.

 

Here is my solution, hoping someone out there finds it helpful.

Get the binary for ffmpeg.exe from: https://www.ffmpeg.org/download.html and click the Windows Build download link.

The only file you will need from this ZIP is ffmpeg.exe.

Create a new folder on your desktop, copy in your images (.PNG or .JPG, whatever you’re converting), and copy in ffmpeg.exe.

Create a new text file and change the file extension to .BAT (Batch Script).

Pop in the following code.

::Import screenshots/photos, and export them into a MP4 to be uploaded for digital signage displays or other uses.

::This creates a "short-format" list of any .PNG files in a list by listing the files in a loop, and outputting to a text file called images.txt. If you need to adjust to .JPG or .GIF, edit below.
::The images.txt file will be fed into ffmpeg for processing of video files.
::If you ever need "long-format" (C:\Folder\image1.png vs image2.png) you can put /r after the "for" command.
for %%a in (*.PNG) do (
    echo file '%%a' >> images.txt
)
::This requires the file "ffmpeg.exe" be in the same directory as the photos
::Input Frame Rate - 0.1 frames per second = 1 image per 10 seconds. 
::File -- Add together the Input of images.txt
::Video Format - libx264 inside of a .mp4 container
::Output Video Frame Rate - 30fps (required for a lot of digital signage systems to actually process the video, don't worry, size doesn't increase very much)
::Name - File Name (NewVideo.mp4)
::Yes - Overwrite Prompt
ffmpeg.exe -r .1 -f concat -i images.txt -c:v libx264 -pix_fmt yuv420p -r 30 NewVideo.mp4 -y

::Deletes the images.txt format so images don't double-up.
del /q images.txt

::Waits for user input before closing the command prompt, to make sure everything runs propertly.
PAUSE

 

RemoteApp – Auto Configure and Setup Shortcuts

RemoteApp Auto-Configure on Logon for Domain Joined Computers

Tired of having to train users to configure RemoteApp? Tired of doing it for them? Use the following script to automatically deploy RemoteApp on Windows 7 and Windows 10.

 

Note: This procedure expects your users to be using a domain logon that the credentials match the RemoteApp server. If local creds are different from Domain Credentials, you may want to remove the “WorkspaceSilentSetup” argument later.

 

WSX File Prep

Take the following code in Notepad, replace bold with your RemoteApp server, and save to a filename “SetupRemoteApp.wsx”. Place this file in your NETLOGON directory (e.g. \\domain.local\NETLGOON)

<?xml version="1.0" encoding="utf-8" standalone="yes"?>

<workspace name="Work Resources" xmlns="http://schemas.microsoft.com/ts/2008/09/tswcx" xmlns:xs="http://www.w3.org/2001/XMLSchema">

 <defaultFeed url="https:/remote.company.com/RDWeb/Feed/webfeed.aspx" />

</workspace>

 

 

GPO Deploy Script

Create a GPO to install a shortcut in the Startup Folder. After a single login of any domain user, all future domain user’s who log in to that computer will have the .WSX automatically execute, setting up their RemoteApp config.

User Configuration > Preferences > Windows Setttings > Shortcuts

Name: Setup RemoteApp

Action:Replace

Target Type: File System Object:

Location: All Users Startup (%allusersprofile%\Microsoft\Windows\Start Menu\Programs\StartUp)

Target Path:C:\Windows\System32\rundll32.exe

Arguments:tsworkspace,WorkspaceSilentSetup \\domain.local\NETLOGON\SetupRemoteApp.wsx

Icon Index: Pick one, I like 12, a computer chip 🙂

Common Tab > Remove this item when it is no longer applied: CHECK

 

GPO Shortcut to Work Resources Script

Create another shortcut, this one really is a shortcut — to the Work Resources folder that contains all of that user’s programs. You can put both in if you want, the shortcut will only apply if the directory exists.

 

Windows 7 Path: %appdata%\Microsoft\Windows\Start Menu\Programs\RemoteApp and Desktop Connections\Work Resources

Windows 10 Path:%appdata%\Microsoft\Windows\Start Menu\Programs\Work Resources (RADC)

 

User Configuration > Preferences > Windows Setttings > Shortcuts

Name: Remote Apps

Action:Replace

Target Type: File System Object

Location: All Users Desktop

Target Path:%appdata%\Microsoft\Windows\Start Menu\Programs\Work Resources (RADC)

Icon Index: Pick one, I like 3, a standard folder

Common Tab > Remove this item when it is no longer applied: CHECK

 

 

Office 365 – Hard Linking Azure AD Connect Users to Office 365 Accounts

Wow, now talk about a niche issue!

You’ve setup Microsoft Azure Active Directory Connect, to sync the usernames/passwords with your Office 365 accounts. However, some of the O365 accounts were already in use when you created your Active Directory domain.

There are two major reasons to do this:

  1. Your staff user accounts are linked with their Office 365 account — one password synced between accounts, change one, you change the other.
  2. Your users don’t have to activate their Office 365 ProPlus every time on a terminal server, this requires Password Syncing + Seamless Single Sign-On (a checkbox really…).
    1. This previously used to require Active Directory Federated Services, a god-awful nightmare of configuration and server setup that doesn’t make sense for a small business.

During the initial setup of Azure AD Connect, it will auto-sync, creating some users that are very close in name, but completely different in account (GUID). Your goal is to get the Local Active Directory account to be directly linked to the Office 365 account (with email and other goodies already active that you don’t want to lose).

 

The process of using Powershell to directly tap into O365 and link the two accounts is called Hard-Linking. There is also Soft-Linking, which only happens when a local AD user is first created, or when AD Connect is initially setup — the email field in Active Directory is matched to the email field in Office 365. There is an IDFix tool provided by Microsoft, in my experience it’s worthless. If both accounts are already live, you have to do hard-linking.

For starters, add the UPN (User Principle Name) suffix of your O365 domain. For example, if your internal AD domain is: cn.company.com, but your O365 domain is company.com, go into Active Directory Sites & Trusts > Right-Click Server > Properties > Add UPN Suffix: company.com.

This will give you the option in Active Directory Users and Computers to change your account names from user@cn.company.com, or even main\user, into an email address format: user@company.com. Edit the properties of any account you want synced to match your email domain.

 

The goal is to take the Active Directory Object GUID, and over-write the O365 Immuatable ID with the AD GUID. This will force them to link on their next Delta sync (generally 2-10 minutes). However, you can’t have a single GUID on two different accounts… So you have to blow away one of the 365 accounts — the duplicate that was unnecessarily created.

This gets slightly messy, and sort of dangerous — make damn sure you know what you are deleting through Powershell! Screw up and *poof* goes a user’s O365 email and file storage.

 

The code:

#Dan Kruse
#October 6th 2017
#How to hard-link a mismatched Active Directory Account to an Office 365 account.
#Run this on Powershell on the Active Directory Server running Azure AD Connect.

#Allow Remote Scripts To Run 
Set-ExecutionPolicy RemoteSigned

#Store Office 365 Global Admin Creds and connect to MS online 
$credential = Get-Credential 
#You will be prompted to enter a login, use a 365 Global Admin account.
Import-Module MsOnline 
Connect-MsolService -Credential $credential

#After adding the UPN Suffix of the email domain, change the user's Account Tab in Active Directory to match their email (e.g. jsmith@company.com)

#Obtain the ObjectGUID of the Active Directory account and load it into a variable
$guid = (Get-ADUser -Identity johns).ObjectGUID
$immutableid=[System.Convert]::ToBase64String($guid.tobytearray())

#Attempt to write the GUID to the valid 365 Account, it should fail...
Set-MsolUser -UserPrincipalName jsmith@company.com -ImmutableId $immutableid

#If/When you get a uniqueness violation/SourceAnchor
#Make **absolutely sure** this user doesn't have any email (Exchange Online Plan 1) license associated with them.... For duplicate accounts ONLY
#Delete the empty/unnecessary O365 account recently created by the sync.
Remove-MsolUser -UserPrincipalName johns@cn.companyname.com

#The GUID is still active until you purge the user from the Office 365 recycle bin, this perma-deletes the account, no going back.
Remove-MsolUser -UserPrincipalName johns@cn.companyname.com -RemoveFromRecycleBin

#Now Hard-Link the user with the Set-MsolUser command from before (again, this time it should go through with no message, just a successful command run)
(Previous Set-MsolUser command above)

#Sync Active Directory to O365, deletions are immediate, password syncs are 2-10 minutes.
Start-ADSyncSyncCycle -PolicyType Delta

 

Mikrotik VPN – L2TP/IPSec Server for Remote Clients (Windows/Android/iOS)

Mikrotik VPN – L2TP/IPSec Server for Remote Clients

If you’re looking for a quick guide for configuring a Mikrotik VPN Server, allowing remote clients to connect into your building controlled by a Mikrotik Router, you’ve come to the right place.

This guide was written for Mikrotik RouterOS v6.41  in September 2017. It presumes you have your main (edge) router as a Mikrotik device, and are NOT behind a double-NAT.

Single-Nat: Modem > Router > Devices.

Double-Nat: Modem > Router > Router > Devices. If your Mikrotik Router has a WAN IP in the ranges of: 192.168.X, 10.X, or 172.16.X, it’s a double-NAT.

 

Alrighty, let’s get started!

There are two parts of a L2TP Server:

  1. L2TP VPN Protocol – Creates the link between two locations
  2. IPSec Encryption – Secures and protects the link

Configure L2TP Server, under PPP (Point-to-Point Protocol)

PPP > Interface > L2TP Server
  Check "Enabled" to turn on the L2TP Server
  Default Profile: default
  Authentication: Check only "mschap2"
  Use IPsec: Yes
  IPsec Secret: YourPreSharedKey
  Caller ID Type: IP Address
  
PPP > Profiles > Default (Create your rules for users)
##If you have multiple bridges to separate your network, create a profile for each and specify the bridge, otherwise ignore.
  Local Address: IP of your local Mikrotik Router (e.g. 192.168.1.1 or 10.10.10.1)
  Remote Address: DHCP pool
  DNS Server: IP of your DNS server/router or 8.8.8.8 (Google DNS)
  
PPP > Secrets (Create your users)
  New (+)
  Name: Username
  Password: UsersPassword
  Profile: default

 

Configure IPSec Encryption

IP > IPsec > Peers
  New (+)
  Address: 0.0.0.0/0 (for allowing any internet IP to attempt to connect)
  Port: 500
  Auth Method: pre shared key
  Exchange Mode: main l2tp
  Secret: YourPreSharedKey (Must match the PSK from PPP > L2TP Server)
  Advanced Tab
    Policy Template Group: default
    Send Initial Contact: Enabled
    NAT Traversal: Enabled
    My ID type: auto
    Generate Policy: port override
    Proposal Check: obey
  Encryption Tab
    Hash Algorithm: sha1
    Encryption Algorithm: Check: 3des, aes-128
    DH Group: Check: modp1024
    
IP > IPSec > Proposals
  Edit Default
  Auth Algorithms: Check: sha1
  Encryption Algorithms: CVheck: 3des, aes-128 cbc
  PFS Group: modp1024

Configure Firewall

IP > Firewall > Filter Rules
  New (+)
  VPN Rule
    Chain: input
    Protocol: 17 (udp)
    Dst. Port: 500,1701,4500
    Action: Accept
  Move rule higher up in the list (above any WAN block rules)
  
IP > Firewall > NAT
  New (+)
  Chain: srcnat
  Out. Interface: bridge (Your internal network bridge)
  Action: Masquerade

 

Configure Client Connection

There are an infinite number of devices that can be configured. I’m going to configure the most common — A Windows 10 L2TP VPN Client, built into the Operating System.

 

Start > Network and Sharing Center
Setup a new connection or network > Connect to a workplace (VPN)
No > Create a new connection

Use my internet connection (VPN)
Internet Address: Your Routers WAN IP (e.g. vpn.company.com, or static IP (e.g. 96.200.200.75)
Destination Name: Your name for this connection
Remember my credentials: Checked


Go to Adapter Settings > Right-Click VPN Connection > Properties
Security > Type of VPN: L2TP/IPSec
Advanced Settings> Use Preshared Key for Authentication: Enter your Pre-Shared Key from the your L2TP IPsec Secret (under PPP > Interfaces > L2TP Server).
Allow these protocols: Check Only: Microsoft CHAP version 2


In Windows 10 - You have to manually re-enter the PSK and saved credentials in a separate menu....

Right-Click VPN Connection > Connect
Select in list > Advanced Option > Edit
VPN Type: L2TP/IPSec with Pre-Shared Key: Enter Pre-Shared Key
Type of Sign-in Info
Username (From PPP > Secrets)
Password (From PPP > Secrets)
Connect

 

You should now be connected to the internal LAN of your Mikrotik network. Attempt pinging devices by IP to confirm connectivity.

 

NETBIOS does not work through the VPN — but FQDNs do.

For example, server1 will not resolve.

Server1.domain.local will resolve

If you absolutely need to resolve by local name, create a WINS server, and assign its IP within the PPP Profile for the WINS Server field.

 

If you need help diagnosing your VPN connection:

System > Logging
New (+)
Create Three Topics: l2tp, ppp, and ipsec
Action: Memory

From here you will be able to see logs under "Log" and google your solution where something may need adjusting.

Crypto Ransomware Prevention – File Server Resource Manager – PowerShell

After spending the last five hours coding like crazy, I’ve got a deployable, reliable, persistent solution. This is one of many Crypto Ransomware prevention strategies. Others are locking down the AppData folder, which could easily break some programs, using AppLocker (Windows Enterprise only), or in this case, protecting file-shares. This strategy — is the file-share canary.

Most Crypto Malware like CryptoLocker, Locky, Cryptowall, and WannaCrypt all search out for file shares containing common content like .TXT, .DOCX, .PDF, and either encrypting the entire file, or just the first 64-128 Bytes of the file, enough to make it unusable. They also drop a notifier, such as “You’ve_Been_Hacked.TXT” with links for paying by BitCoin in the hopes of getting a decryptor program that might work.

The best resolution to being hit by crypto is a backup restore, but this post is for a preventative measure — aiming to stop the need for the backup. Still create hourly, or at worst, daily backups — don’t rely only on this single script!

We are going to use the Microsoft Windows Server 2012 R2 File Server Resource Manager File Screens method to detect any changes made to certain directories, and upon any change, block that user’s access to all file-shares (SMB) immediately. In reality, it takes about 2-3 seconds to lock the user out of everything. Another common method is to disable the Server service, “LanManServer + NetLogon”, which breaks all shares, a bit too extreme in my opinion.

 

Below is the code, enjoy, good luck, and hoping it helps you out.

There are two scripts:

  1. Crypto_Malware_Prevention.ps1, which installs File Resource Server Manager, creates the folders, creates SMB Shares (“_Honey”, and “zzHoney”, for ascending and descending), sets permissions, and configures the File Screens.
  2. Crypto_Malware_Prevention_User_Disable.ps1, which is called upon as a command/action by FRSM, to ban the user upon touching any of the files.

It is up to you to populate the _Honey folder with content, this part is not scripted, you’ll need to unload a ZIP full of .DOCX or .PDF files inside.

Crypto_Malware_Prevention.ps1

###################
#Server Settings  
#dankrusework (at) gmail (dot) com
#itimagination.com
###################

#Install File Resource Manager 2012 and 2012 R2
Install-WindowsFeature -Name FS-Resource-Manager -IncludeManagementTools

#Change the interval between how often the action can be taken.
Set-FsrmSetting -EventNotificationLimit 1 -CommandNotificationLimit 1

#Path to Protect.
#Simpler to map two SMB Shares to one folder for management.
$path1 = "C:\Shares\_Honey"
New-Item $path1 -type Directory
New-SMBShare -Name "_Honey" -Path $path1 -FullAccess Everyone
New-SMBShare -Name "zzHoney" -Path $path1 -FullAccess Everyone

#Assign Everyone Full Control NTFS Permissions for the path
CACLS $path1 /E /T /G Everyone:F

########
#Script#
########
#Create the Action Command to be implemented (Block User, Stop Service, etc)
$Command = New-FSRMAction Command -Command "%SystemRoot%\SysWOW64\WindowsPowerShell\v1.0\powershell.exe" -CommandParameters "C:\CryptoBlockUser.ps1" -SecurityLevel LocalSystem -RunLimitInterval 1 -KillTimeOut 1

#Create the Warning Event to record the source
$WarningMessage = "User [Source Io Owner] attempted to modify [Source File Path] to [File Screen Path] on server [Server]. This file is in the [Violated File Group] group, and may possibly indicate a Ransomware infection. Your account has been blocked from accessing the server. After the computer has been cleaned, run the following command `"Get-SmbShare -Special `$false | Unblock-SmbShareAccess -AccountName `"USERNAME`" -force`" to remove their block from all shares on that server."

$Warning = New-FSRMAction Event -EventType Warning -Body $WarningMessage -RunLimitInterval 1

#Create a File Group - desktop.ini and thumbs.db may be created automatically by simply browsing but not editing.
New-FsrmFileGroup -Name "Crypto_HoneyPot_Detection" -IncludePattern @("*.*") -ExcludePattern @("*.ini","*.db*")

#Create a File Template using the existing FileScreens
New-FsrmFileScreenTemplate "Crypto_Honeypot" -IncludeGroup "Crypto_HoneyPot_Detection" -Active:$False -Notification $Command,$Warning

#Assign the template to the path of the share
New-FsrmFileScreen -Path $path1 -Template "Crypto_Honeypot" -Active:$false

 Crypto_Malware_Prevention_User_Disable.ps1

#############################################
#Save this script to C:\CryptoBlockUser.ps1
#dankrusework (at) gmail (dot) com
#itimagination.com
#############################################
#.PS1 Script to ban user running Crypto Malware
#One second delay to give script enough time to grab newest event logs
sleep -Seconds 1

#Looks in event log for the custom event message generated by the file screen audit. Input's username of the offender into a variable.
$RansomwareEvents = Get-WinEvent -FilterHashtable @{ logName = 'Application'; ID = 8215 } -MaxEvents 1 -Ea 0
$username = ($RansomwareEvents.message).split()[1]
$username = $username -replace ".*\\"

#Blocks SMB share access for user
Get-SmbShare -Special $false | Block-SmbShareAccess -AccountName $username -force

Results

Attempting to create any file in either of the shares will result in Event ID 8215, followed by the loading of the User_Disable Powershell Script.

Reversing the Block

Once you have successfully wiped and reloaded the computer, or purged the crypto malware, it’s time to clear the user’s block. Run the following code, replacing the USERNAME entry.

Get-SmbShare -Special $false | Unblock-SmbShareAccess -AccountName "USERNAME" -force

 

Monitor

FRSM has a built in e-mail functionality, which is a Notification action. I personally choose to use our RMM tool, Kaseya, to simply send our team an alert upon detection of Event ID 8215, something I find more reliable than an externally hosted email server, Office 365. It just takes one password change for the alert to not go through.

 

Hoping you found this helpful, let me know if you have anything to add, thanks 🙂

Powershell – Checking for Pirated Windows and Office Licenses

Checking for Pirated Windows and Office Licensing with Powershell

We just got a new non-profit client, and the old IT provider sold them hardware and charged for licenses, while using AutoKMS to falsely activate their Windows and Office licenses. Now I have to identify which machines are pirated and get new licenses purchased. The story of my life — cleaning up other people’s messes.

If you find yourself in a similar predicament, hopefully this code is helpful to you. I try to use single-liner code whenever I can, for reliability and ease of editing.

Because of the complexity of the text outputs — it can be extremely varied, I feel it is best to review the TXT files individually. I only have 70 machines to run through their TXT files. If you have thousands of files, well, at least the commands can get you the content.

This Powershell code will run on any Win7+ machine, and outputs a text file with the machine’s name and domain inside. The file is then copied to a temporary file-share I have made (everyone read/write), solely for the collection of these TXT files. Once they are collected, I will remove the share. Then I can ZIP up the TXT files, and pop everything into an Excel spreadsheet for providing a report to management on what to purchase. Just swap out “SERVERNAME\PUBLICHSHARE for your environment.

Enjoy!

#Save a TXT document for storing the license data, with the machine-name, and print the machine's name and domain into the TXT file.
echo $env:computername,$env:userdnsdomain | Out-File "\\SERVERNAME\PUBLICSHARE\LicensingCheck.$env:computername.txt"

#Echo the license statuses into the TXT file. Appending keeps the script from over-writing the file.
Get-CimInstance -ClassName SoftwareLicensingProduct | where PartialProductKey | select Name, LicenseStatus, LicenseFamily | FL | Out-File "\\SERVERNAME\PUBLICSHARE\LicensingCheck.$env:computername.txt" -append

#Write the licensing definitions into the text file.
echo "Definitions" "0 Unlicensed" "1 Licensed" "2 Out-Of-Box Grace Period" "3 Out-Of-Tolerance Grace Period" "4 Non-Genuine Grace Period" "5 Notification - Note that this includes Temporary Licensing Office 365, Student for 2 years, etc" "6 Extended Grace" | Out-File "\\SERVERNAME\PUBLICSHARE\LicensingCheck.$env:computername.txt" -append

Example Result File

COMPUTERNAME
CN.COMPANYNAME.COM

Name          : Office 15, OfficeO365ProPlusR_Subscription1 edition
LicenseStatus : 5
LicenseFamily : OfficeO365ProPlusR_Subscription1

Name          : Windows(R), Professional edition
LicenseStatus : 1
LicenseFamily : Professional

Name          : Office 15, OfficeStandardVL_MAK edition
LicenseStatus : 1
LicenseFamily : OfficeStandardVL_MAK


Definitions
0 Unlicensed
1 Licensed
2 Out-Of-Box Grace Period
3 Out-Of-Tolerance Grace Period
4 Non-Genuine Grace Period
5 Notification - Note that this includes Temporary Licensing Office 365, Student for 2 years, etc
6 Extended Grace

Mikrotik and Wireless Interference – Deploying High Density WiFi with CAPsMAN

Mikrotik and Wireless Interference – Deploying High Density WiFi with CAPsMAN

This post is brought to you by over 100 hours of blood, sweat, and maybe a few tears, in making an optimal Mikrotik-based high density wireless system. One of the hardest projects I’ve ever done, but wow it feels good to be at the end. How to configure a wireless network using Mikrotik Access Points, and handling the wireless interference that comes from high-density deployments.

Overview

Controlled Access Point System Manager, what a mouthful. It can be your best friend in managing a very complex wireless network. When it’s set up correctly, you can just connect a WAP, it will automatically pull its settings based on it’s name, with multiple SSIDs going to separate networks (datapaths), able to cut through interference and give your clients a positive wireless experience.

When setup poorly, expect a world of pain to crash down on you, from intermittent connectivity (which plagues all wireless systems with interference), non-automatically provisioning devices, and bogged down WAPs.

The goal of this very long post is to set everything up correctly.

We will cover the following:

  1. Configuring CAPsMAN
    1. Dynamic Provisioning by Regular Expressions (RegExp)
    2. Datapaths
      1. Local Forwarding / Client to Client Forwarding
    3. Configurations
    4. Channels
    5. Security Cfg
    6. Access List
  2. Access Rates – The Answer to High Density interference
  3. Setting Mikrotik WAP to CAP mode by button presses

Configuring CAPsMAN

Make sure your device is updated to the newest BugFix or Current release: System > Packages > Check for Updates. Once done, you’ve got CAPsMAN v2.

 

  • For starters, turn on CAPsMAN:
    • CAPsMAN > Interfaces > CHECK: Enabled > OK

Dynamic Provisioning

  • Provisioning is the rules of assignment of settings to a WAP. Basically, if the device asking for settings (a WAP/CAP) matches these rules, it will be given these settings.
    • Example: If the AP is named, “AP06”, it will be dynamically-enabled (approved/adopted), and given the master config “Private WiFi” and the slave config “Guest WiFi”.
  • If you set your Radio MAC to the default of: 00:00:00:00:00:00, it will accept connections on any of the router’s interfaces.
    • Action: Create Dynamic Enabled, will accept any CAP device asking for a config.
  • Regular Expressions
    • For this purpose, Regexp is a rule that allows you to approve devices by name.
    • Example:
      • I have 15 APs, numbered: AP01-AP15
      • I want APs 01-08 to have config1, and APs 09-15 to have config2.
      • Regexp Example (Config1): AP0[1-8]
        • AP0 is static, this must match the first part of the identity.
        • [1-8] means the character after 0, can be different, but within the range 1-8.
      • Regexp Example (Config2): AP09|AP1[0-5]
        • AP09 is static, this matches the AP with the exact identity of “AP09”
        • The Pipe Symbol ‘|’, above the enter key, stands for “or”.
        • AP1 is static, range for the character after 1 can be 0-5, so this matches APs 10-15
  • Master Configuration
    • You’ll need to define your configurations later, but a config is the “profile” of everything from SSID to password to channel used to transmit power. You can stack configurations as slaves, the master defines the major settings though, like channel used to broadcast and transmit power.
  • Slave Configuration: The slaves are more for data-paths (where network traffic will be routed to) and different SSIDs/Passwords. You could have one master config, and for example, 3 other SSIDs as slave configs.
    • It is recommended to not use more than 4 SSIDs per WAP to reduce on beacon-time (gobbles up a good chunk of usable broadcasting frames).
  • Name Format
    • I recommend always using Identity. This will make it much easier to figure out which Radios belong to what device. You will need to edit the identity though of each AP, under System > Identity. (Add a password to each AP while you’re at it! System > Password).

Datapaths

In short, traffic connected to this SSID, will go into this network/bridge. This feature through CAPsMAN was a life saver for a multi-subnet network, because some SSIDs had to be isolated from each other, rather than having to VLAN every SSID to each WAP through switches to get to their respective networks, the Mikrotik Router/CCR simply pops the traffic into it’s respective bridge.

subfloor-datapath

Local forwarding means all of the traffic from the client goes directly to the master router for well, routing.

Client-to-Client forwarding means clients connected to the same AP can talk directly to each other, no need to go all the way through the network just to talk to someone in the same room as you.

I recommend having Local Forwarding off: This means click on the arrow that unlocks the setting, and leave the box unchecked.

I recommend having Client to Client forwarding on: expand the setting, and check the box.

 

Configurations

A configuration is a profile containing other settings, like SSID, channel, and password (Security Cfg).

In your configuration, define your SSID, I also recommending setting a Max Station Count to keep your APs from getting overloaded. Use the “rule of 15”, that is, 15 clients per physical antenna max. You’ve got a 2×2 wireless access point? Great! After you have more than 30 clients connected, your WAP will be brought to its knees and all clients will be miserable with poor connectivity. Add up your antennas, and reduce by a few. For example, on a Mikrotik WAP, which is 2×2, I set my Max Station Count to 25.

  • HW Retries
    • In the event a wireless frame fails or is dropped, how many times the WAP will attempt to resend the frame before moving on. Default is 15, I recommend using 4 if you are in high-density.

Channels

Though you can define your frequencies explicitly, and it can help a lot with interference, it can be very challenging to manage. If you do decide to define your frequencies, only use channels 1, 6, and 11, as they offer full spatial separation from one another — less interference. If you don’t manually specific channels, the AP will do a frequency scan and look for the least-busy channel, and select that.

Always use 20MHz for 2.4GHz. This is the width of the channel a client can use to transmit speed, the larger the width, the higher the maximum speed can be. In reality, unless your clients need more than 54Mbps of traffic, there is no benefit of going 40MHz. You really start to see gains in the 5GHz spectrum, or in point-to-point links over large distances. 20MHz is an absolute must for high-density.

I recommend having a few different power levels, here is my go-to example:

  • 12dB-20MHz-nchannel
    • Frequency: Blank (automatic based on channel scan)
    • Width: 20MHz
    • Band: 2ghz-onlyn
      • By not allowing a or b clients you allow for much more efficient bandwidth utilization. If you need some older equipment connected, you may need to use 2ghz-g/n.
    • Extension Channel: Disabled
      • Extension Channel is 20Mhz + another range.  Mainly useful in very small offices or homes, effectively bumps you up to 40MHz for higher speeds.
    • Tx Power: 12dB
      • Depends on your device, if you’ve got your own external antennas, don’t go too high or risk burning out the amplifiers.
  • 16dB-20MHz-n
    • Everything is the same except Tx Power is 16dB.
  • 18dB-20MHz-n
    • Everything is the same except Tx Power is 18dB.

More power does not mean better WiFi. Just as you amplify your signal, you also amplify noise. As power goes up, sensitivity goes down, and vice versa. You will have much better coverage and usable WiFi with more WAPs running at lower power, rather than just one super-powerful WAP.

If you have overlapping APs, less is more, counter-intuitive of what you may naturally think. “Signal is bad and I’m dropping packets, boost the range, that will help!” — Wrong! Higher loads require more ability to get the signal through the noise. If you’ve got high density loads, lower power will give you FAR better results, at the expense of reduced range.

Security Config

The password and security type that will be assigned to a config. If there is no security config applied to a config, it will be an open network.

Recommended settings:

  • WPA2 PSK
  • Encryption: AES CCM
  • Group Encryption: AES CCM
  • Passphrase: YourPassword

One important note — Group Key Timeout, a critical setting for Apple devices like iPhones or MacBook Pros, can only be set via the Winbox terminal. I recommend using 1 hour as your minimum. This setting was added to CAPsMAN in 6.38.5.

Example terminal code:

/caps-man security set Security-Config group-key-update=1h

To confirm:
/caps-man security get Security-Config
print

 Access List

For “ghetto-roaming”. That is, non-zero-handoff. If you want seamless roaming, you’ll need to spend more than $40/Mikrotik WAP, and even Ubiquiti’s $200 WAPs are incredibly unreliable for zero-handoff. To get true seamless roaming you’re looking at $400/WAP minimum. However, if you are ok with a 0.5s-3s drop while switching from WAP to WAP, this has what you need:

Access List, at the top add an accept rule:

  • -88..120
    • Action: Accept
    • If your signal is between -88dB and +120dB, you are allowed to connect.
  • -120..-89
    • Action: Reject
    • If your signal drops below -89dB, you’re kicked from this AP, go find another AP to connect to that has a stronger signal.

Your usable signal depends on the equipment you are using. With Ubiquiti, expect signal to become unusable after -75dB. For Mikrotik, I tend to get unusable signal ariybd -86dB. The reject rule goes into effect once the client signal drops below the defined strength for about 2 seconds.

From here, it’s entirely on the client to choose how aggressively (quickly) to roam to another AP. General results are between 1-3 seconds, but some very crappy old (<2004)equipment can take up to 8-10s to flip over to another available AP.

Access Rates — How to Handle Massive Interference

This is the big one, your very definition of handling high-density interference. By default, all access rates are approved, everything from 1Mbps to 54Mbps. This is the difference between standing 5 feet from the WAP, and being unable to connect or having 90% packet loss due to interference, and everything working flawlessly.

You could get a Ph.D. on access rates alone, but I’ll do my best to explain what is going on.

The issue is time, you only have so long to transmit a signal between your WAP and client devices. Let’s use some fake numbers, in reality, it’s in the microsecond timescale, but let’s use a scale of 10 seconds.

Remember, there is only one “wire” — the air! So only one device can talk at a time.

  1. T+1s
    1. The beacon (announcement of the SSID) takes up 1 second.
  2. T+3s
    1. The WAP speaks, sending data to your laptop for 2 seconds, the laptop listens.
  3. T+5s
    1. The laptop responds for 2 seconds, the WAP listens.
  4. T+7s
    1. A cell-phone receives data from the WAP.
  5. T+9s
    1. The cell-phone responds with data to the WAP.
  6. T+10s
    1. The WAP announces the frame is over, we have 10 more seconds to talk.

 

What if we were able to let everyone speak faster. So the laptop doesn’t require 2 full seconds to speak its sentence/frame (1Mbps), it only needs 0.1s (54Mbps). Because devices are talking more quickly, we can squeeze in more conversations — more devices, more load!

 

This is the essence behind access rates. The faster you can talk, the more load you can handle. The downside is you must have a good signal to speak quickly and have the WAP still understand you. If you’re 200 feet away with -85dB signal, you can’t talk as quickly, maybe 6Mbps, you’re taking up more time…. load is reduced and interference goes up if there are a lot of people or cell-phones idling in pockets, transmitting at 1Mbps….

So how do we handle this? — Add more access points for the range issue, and require everyone who wants to speak/communicate to only speak quickly.

 

Enter: Basic and Supported Rates.

Basic means minimum. This is the minimum speed the WAP will speak with your device. If it’s your house, 1Mbps is fine. If it’s a stadium with 10,000 people, try 24Mbps or 36Mbps as the minimum. You only check a single box for basic. From there, how high do you want to go? I personally recommend for a high-density, high-interference environment, to use 36Mbps as your minimum, and 36, 48, and 54 as your supported rates.

MCS Rates: MCS is a series of overlapping rates, why have just one stream when you can layer them for more speed?

http://mcsindex.com/

For example, MCS Index 3, is the speed 26Mbps on 802.11n. I recommend enabling all MCS Indexes which are not QPSK or BPSK. This would mean, check all boxes except for: 0,1,2,8,9,10,16,17,18,24,25,26. Enabling the MCS Indexes will massively boost your speeds for 802.11n.

 

VHT MCS: same as above, but it’s for 5GHz rather than 2GHz,  they are restricted into the ranges of 0-7, 0-8, and 0-9. I recommend 0-9.

Many cell-phones idle at 1Mbps to stay connected to their WAP but not use much power. However, we don’t want 20 cell phones in pockets, not transmitting, to take up active slots on our WAPs. If your phone tries idling for low power, it gets kicked off because it’s access rate is low. The moment you wake up the phone, you’ll reconnect back at the full-power rates and be able to browse the internet.

 

Mikrotik – Enter CAP Mode

You need to upgrade your packages in order for an AP in CAP mode to be adopted by a CAPsMAN controller. If under “System > Packages”, everything shows 2015, you’re on CAPsMAN v1, your device will not be adoptable by a CAPsMAN v2 controller. Manually update the packages on the Mikrotik AP, the next time it reboots, it will provision according to your CAPsMAN provisioning rules.

This is a step that was surprisingly difficult to learn, hard to find any clear notes on it. Though there is “Quick Set: CAP” option, it never seems to work for me no matter how many devices I try. The best method I’ve found to put a WAP into CAP mode — ready to be adopted by a CAPsMAN controller, is a special set of holding the reset button at boot.

For the WAP:

  1. Unplug power/PoE.
  2. While holding down the reset button, connect power/PoE.
  3. All 4 lights will turn on (booting).
  4. The middle two lights will begin blinking
  5. The CAP light will turn on
    1. LET GO OF RESET!
  6. The middle two lights will flash very quickly for 1 second, and the WAP will reboot, now as DHCP Client (rather than a DHCP Server) and CAP mode enabled, ready to be adopted.

You will know if you are in CAP mode upon logging into an AP, it takes a good 30 full seconds to come back up after going into CAP mode. After it’s been reset, it will either say “ap-bridge” mode — the default for a router, or “cap mode”, ready for being adopted. Now give it a name through System > Identity, such as AP05 or CompanyAP12, whatever naming format you want. Set a password. The CAP should be auto-adopted by your CAPsMAN Controller and pull SSIDs and other settings.

That’s it for now, have fun and good luck!

Mikrotik – Cloud Router Switch – Switch Chip VLANs

 

Mikrotik – CRS – Switch Chip VLANs

Well, this all came in last week — 8x Cloud Router Switches (CRS125-24G-1S), 33x WAPs, 4x BaseBox 2s, and a 12 Port Fiber Switch (CRS212-1G-10S-1S+), enough gear to hook together an a minor-league baseball stadium, fun stuff!

TWhat did I get myself into with this much gear?his post is regarding how to use the CRS Switch Chip. The CRS series operates very differently than the standard RouterOS featureset. The CPU is very weak in these devices — any heavy lifting should be handled internally by the switch chip. Think of it as a separate processor specialized for passing traffic contained entirely within the switch-chip — it can understand VLANs, protocols, and the data passing through without burdening the CPU, but is not intended for functions like firewall rules or Layer3 (IP) routing.

If you are using a CRS, the Switch menu has six additional submenus under it, not visible under a standard RouterOS Router.

  1. ACL – Access Control List — Allow/Deny rules based on MAC Addresses
  2. FDB – Forwarding Database — Cache / Remembered MAC addresses for which ports — E.g. your laptop is connected on ETH23, your desktop on ETH5.
  3. Ports – Physical Ports – A lot fo settings here, the most important is how the ethernet interfaces are linked together.
  4. QoS – Quality of Service – Priority of Traffic under load (VOIP is more important than bulk data)
  5. Settings – Definitions for the switch to use, pretty advanced
  6. VLAN – Virtual Local Area Network — The rules affecting traffic as they pass through the switch, for separating traffic through the use of trunk ports.

We are going to focus on #6, as that is the submenu I find most useful, and have spent too much time working on 😉

 

Trunk vs Access

Let’s start with a simple picture of a trunk port, vs access ports.

Trunk: A “master” wire, that carries the data of multiple VLANs to another destination to be split up — on the other side is another smart/managed switch or a router able to understand VLANs.

Access: A “standard” wire, that carries data to/from devices like computers or printers.

In this very simple example — not including a router to transfer traffic between VLANs or to the internet– computers on VLAN100 can only talk to other computers in VLAN100, computers in VLAN300 to other machines in VLAN300, and they all share a single trunk fiber (SFP) carrying the data of all three VLANs.

VLAN Tagging

A VLAN Tag is an ID number assigned to data as it travels through an interface. The tags are used to define where the traffic ends up — what network it belongs to. Most commonly, traffic comes in as untagged access traffic (VLAN 0,) the switch then “tags” the traffic with a VLAN ID (e.g. VLAN100) as it passes through a specific port. Now that the switch has a tag, the traffic will be directed somewhere depending on what rules the Switch Chip or Router follow.

Ingress (Inbound) and Egress (Outbound)

Ingress simply means traffic going into the switch, and Egress means traffic leaving the switch. The reason these terms are used instead of inbound or outbound, is Egress/Ingress contains ALL of the data passing through, not just the data that matters, but headers, VLAN tags, MAC addresses, every single 1 and 0 related to the traffic going through. Inbound/Outbound are often related to traffic going into/leaving your site via the internet. Ingress/Egress can be for example, leaving (egress) the master router to be received (ingress) by a switch, which then sends data (egress) to your desktop (ingress).

Configuring VLANs via the Switch Chip

There are three things that matter to get a VLAN working on a Mikrotik Cloud Router Switch.

  • The VLAN Table – What VLANs are allowed to communicate on which ports. It’s a rule-list for which VLANs can talk on which physical plugs.
    • The ports allowed to “Speak” VLAN800 are ETH1, ETH8-20, and SFP1.
    • The ports allowed to “Speak” VLAN900 are ETH1, ETH8, ETH21-24, SFP1.
  • Ingress VLAN Translation – If it comes in (Access) with VLAN X, tag it with VLAN Y.
    • Ingress VLAN Translation, traffic on ports ETH21-24 coming in with a Customer VLAN ID of 0 (Access), will be tagged with Customer VLAN ID 900. Ports ETH9-20 coming in as VLAN0 (access) will be tagged with VLAN800.
  • Egress VLAN Tagging – If it goes out this physical plug (Trunk), add on this VLAN tag.
    • I am using ports ETH1 and SFP1 – either can be used as the trunk port.

That’s all that is needed for the switch chip to assign VLANs. If it comes in on an access (ingress) port, add on a VLAN ID tag, then send out the tag through the trunk (egress). It then depends on the receiving switch/router to understand the traffic it is getting.

If I plugged my laptop into ETH21, I would be on VLAN900. If I plugged my laptop into ETH9, I would be on VLAN800.

 

In this “in-production scenario”, the traffic was going out SFP1, and into SFP2 into a Fiber Switch, which then passed traffic via it’s one ethernet port (ETH1), to the Router’s ETH3.

Getting the traffic to flow between ports is quite straight-forward. Interfaces > VLAN > Add > ID# – apply to each physical interface.

For example, if I want Fibers SFP2, SFP3, and ETH1 to all communicate on the VLAN800 network, I just make a VLAN tag and apply to each physical interface. Each physical interface with that tag on it will be “on that VLAN ID’s network”, able to talk with each other.

In addition, you can still have standard access traffic — for Example, the Cloud Router Switch if it has an IP on it, will still speak “access, VLAN0” on it’s primary port. This can be helpful for standard switching, or managing your switches from a central point. You can stick an IP address onto your trunk (access), in addition to having VLANs assigned under that trunk. Powerful stuff. In my example, ports ETH2-ETH7 are not given a VLAN tag — those are standard access ports, and they will communicate over SFP1 with everything else. In this example, I was connected to ETH5, I would be on standard access traffic. Since SFP1 and ETH are in the switching interfaces I’m just another part of the network, no VLANs involved.

By default, your VLANs are isolated, but the Master Router (which knows everything that is inside the network), may let traffic be visible between them. To stop this, simply use firewall rules on your master router, and block by inbound/outbound bridges, interfaces/VLANS, or IP ranges — depending on what setup you are using.

 

Hoping that was helpful, good luck, and have fun!

Office 365 Powershell – Configure Permissions

Microsoft’s Office 365 is basically Exchange 2016 through a web-page. A lot of the buttons you used to have are now hidden, and can only be access through Powershell.

This post contains raw Powershell code to connect in to your Office 365 instance, and change user permissions over individual parts of mailboxes — either the entire thing, or just a calendar, contacts, or email.

#Define the Office 365 Admin Account credentials. Use an Office 365 admin account (user@onmicrosoft.domain.com/password)
$LiveCred = Get-Credential

#Define the Office 365 Powershell server you are connecting to and which credentials to use
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.outlook.com/powershell/ -Credential $LiveCred -Authentication Basic -AllowRedirection

#Connect / Dial-In to Office 365 Powershell
Import-PSSession $Session



#Ways to check permissions. If you want to assign, just switch out the "Get" at the start to "Add" for new permissions, or "Set" for changing existing permissions.
#For Calendar
Get-MailboxFolderPermission -Identity user1@domain.com:\calendar
#For Mail
Get-MailboxFolderPermission -identity user1@domain.com:\inbox
#For contacts
Get-MailboxFolderPermission -identity user1@domain.com:\contacts
#For the entire account
Get-MailboxFolderPermission -identity user1@domain.com

#If the user is yet added
Add-MailboxFolderPermission -Identity user123@domain.com:\calendar -user userABC@domain.com -AccessRights Owner

#If the user needs full control
Set-MailboxFolderPermission -Identity user123@domain.com:\calendar -user userA@domain.com -AccessRights Owner
Set-MailboxFolderPermission -Identity user123@domain.com:\calendar -user userB@domain.com -AccessRights Owner
Set-MailboxFolderPermission -Identity user123@domain.com:\calendar -user userC@domain.com -AccessRights Owner
Set-MailboxFolderPermission -Identity user123@domain.com:\calendar -user userD@domain.com -AccessRights Owner
Set-MailboxFolderPermission -Identity user123@domain.com:\calendar -user userE@domain.com -AccessRights Owner

#AccessRights Types
Owner (Full Permissions)
Delegate (Owner, but cannot see private)
PublishingEditor (Read/Write/Modify/New)
Editor (Read/Write/Modify)
Reviewer (Read Only)
Contributor (Write Only)

#Reference
https://technet.microsoft.com/en-us/library/dd298062(v=exchg.160).aspx

 

Mikrotik Security Script

Mikrotik Security Script – Protecting a Mikrotik Internet Facing Router

There are a lot of Mikrotik security scripts out there, showing off bells and whistles of how to block extremely specific attacks. Many of these are additional layers of security, the more layers, the safer you can be, at the expense of CPU power.

I needed a security script to protect a small business. The only publicly facing internet services are TCP443 for an internally hosted web-site, and TCP25 with a restricted access rule (whitelist only). The design philosophy is to minimize the number of IP filters. For example, instead of having separate block rules for TCP22, UDP53, TCP3389, TCP5900, etc, load them into a single rule blocking via address list. Invalid traffic used by port-scanners and DDoS’ers will be tarpitted.

Goals

  1. Provide a high level of protection without going over-kill on firewall rules (CPU load).
  2. Redirect client requested DNS queries (UDP 53 to 8.8.8.8 for example) to be forced to use a DNS server of my choosing, in this case, OpenDNS.
  3. Block as much torrent-related activity as we can. Combination of OpenDNS, and interrupting DNS lookups with Layer7 Protocol packet marking.
  4. Block WAN DNS lookups, and block and log LAN based SMTP mailbots and port scanning (NETBIOS).

Hoping this script can be of use to you.

#Disable Unnecessary Services (Winbox only)
/ip service
set telnet disabled=yes
set ftp disabled=yes
set www disabled=yes
set ssh disabled=yes
set api disabled=yes
set api-ssl disabled=yes

#Disable unused packages
/system package disable hotspot
/system package disable mpls

####WAN Rules####
#Don’t let Winbox access (TCP8291) be broadcast to neighbors via WAN
/ip neighbor discovery
set ether1 discover=no

#Blacklist Common Port Lookups for 3 days
/ip firewall filter
add action=add-src-to-address-list address-list=BlackList address-list-timeout=3d chain=input comment="Detect Port Scanners" dst-port=21-23,53,88,135-139,389,445,1433,3306,3389,5900,6667 in-interface=ether1 protocol=tcp
add action=add-src-to-address-list address-list=BlackList address-list-timeout=3d chain=input comment="Detect UDP WAN DNS Lookups to prevent DDoS" dst-port=53 in-interface=ether1 protocol=udp
add action=drop chain=input comment="Drop Blacklisted Hosts to Router" in-interface=ether1 src-address-list=BlackList
add action=drop chain=forward comment="Drop Blacklisted Hosts through Router" in-interface=ether1 src-address-list=BlackList

#Blacklist NMAP Stealth Port Scanners for 3 days (can be abused for DDoS as well)
/ip firewall filter
add action=drop chain=input comment="Drop port scanners" src-address-list=PortScanners
add action=add-src-to-address-list address-list=BlackList address-list-timeout=3d chain=input comment="Add Port scanners to blacklist" protocol=tcp psd=21,3s,3,1
add action=add-src-to-address-list address-list=BlackList address-list-timeout=3d chain=input comment="Add NMAP FIN Stealth scan to list" protocol=tcp tcp-flags=fin,!syn,!rst,!psh,!ack,!urg
add action=add-src-to-address-list address-list=BlackList address-list-timeout=3d chain=input comment="Add SYN/FIN scan to list" protocol=tcp tcp-flags=fin,syn
add action=add-src-to-address-list address-list=BlackList address-list-timeout=3d chain=input comment="Add SYN/RST scan to list" protocol=tcp tcp-flags=syn,rst
add action=add-src-to-address-list address-list=BlackList address-list-timeout=3d chain=input comment="Add FIN/PSH/URG scan to list" protocol=tcp tcp-flags=fin,psh,urg,!syn,!rst,!ack
add action=add-src-to-address-list address-list=BlackList address-list-timeout=3d chain=input comment="Add ALL/ALL scan to list" protocol=tcp tcp-flags=fin,syn,rst,psh,ack,urg
add action=add-src-to-address-list address-list=BlackList address-list-timeout=3d chain=input comment="Add NMAP NULL scan to list" protocol=tcp tcp-flags=!fin,!syn,!rst,!psh,!ack,!urg

#Port Knocking Entry
add action=add-src-to-address-list address-list=AccessRouter1 address-list-timeout=10s chain=input comment="Port Knock for Router Access" dst-port=10000 protocol=tcp
add action=add-src-to-address-list address-list=AccessRouter2 address-list-timeout=10s chain=input dst-port=20000 protocol=udp src-address-list=AccessRouter1
add action=add-src-to-address-list address-list=AccessRouter3 address-list-timeout=1h chain=input dst-port=30000 protocol=udp src-address-list=AccessRouter2
add action=add-src-to-address-list address-list=AccessRouter4 address-list-timeout=1h chain=input dst-port=40000 protocol=tcp src-address-list=AccessRouter3
add chain=input comment="Allow in Winbox" dst-port=8291 in-interface=ether1 protocol=tcp src-address-list=AccessRouter4

#Allow through good traffic (started from LAN)
add chain=forward comment="allow established/related connections through the router" connection-state=established,related

#Block DDoS Attacks
/ip firewall filter
add action=tarpit chain=input comment="Suppress DoS attack" connection-limit=3,32 protocol=tcp src-address-list=DOSattacker
add action=add-src-to-address-list address-list=DOSattacker address-list-timeout=1d chain=input comment="Detect DoS attack" in-interface=ether1 connection-limit=20,32 log=yes protocol=tcp
add action=accept chain=input in-interface=ether1 comment="suppress ping flood-0:0 and limit for 5pac/s" icmp-options=0:0-255 limit=5,5:packet protocol=icmp
add action=accept chain=input in-interface=ether1 comment="suppress ping flood-3:3 and limit for 5pac/s" icmp-options=3:3 limit=5,5:packet protocol=icmp
add action=accept chain=input in-interface=ether1 comment="suppress ping flood-3:4 and limit for 5pac/s" icmp-options=3:4 limit=5,5:packet protocol=icmp
add action=accept chain=input in-interface=ether1 comment="suppress ping flood-8:0 and limit for 5pac/s" icmp-options=8:0-255 limit=5,5:packet protocol=icmp
add action=accept chain=input in-interface=ether1 comment="suppress ping flood-11:0 and limit for 5pac/s" icmp-options=11:0-255 limit=5,5:packet protocol=icmp

#Drop Unsolicited Traffic from WAN
/ip firewall filter
add action=drop chain=input comment="Drop Unsolicited WAN Traffic" connection-state=invalid,related,new in-interface=ether1

####LAN Rules####
#Redirect clients in a specific interface-list (guest bridges) to our DNS Servers (OpenDNS), and prevent from using their own DNS Servers (Google, Comcast, etc) to bypass filtering
/ip firewall nat
add action=dst-nat chain=dstnat dst-port=53 in-interface-list=list-guests protocol=udp to-addresses=208.67.222.222 

#Block Torrenting DNS Lookups
/ip firewall layer7-protocol
add comment="P2P DNS Blocking" name=p2p_dns regexp="^.+(torrent|thepiratebay|isohunt|entertane|demonoid|btjunkie|mininova|flixflux|vertor|h33t|zoozle|bitnova|bitsoup|meganova|fulldls|btbot|fenopy|gpirate|commonbits|rarbg|torlock|kat|1337x).*\$"
/ip firewall mangle
add action=mark-packet chain=postrouting disabled=no layer7-protocol=p2p_dns new-packet-mark="p2p download" passthrough=no
/ip firewall filter
add action=drop chain=forward comment="Block P2P_dns Packets" disabled=no layer7-protocol=p2p_dns

#Block basic Torrenting Traffic
/ip firewall filter
add action=drop chain=forward comment="Block General P2P Connections" disabled=no p2p=all-p2p
add action=drop chain=forward comment="TORRENT No 1: Drop classic torrents" disabled=no p2p=all-p2p
add action=drop chain=forward comment="TORRENT No 2: Drop outgoing DHT" content=d1:ad2:id20: disabled=no dst-port=1025-65535 packet-size=95-190 protocol=udp
add action=drop chain=forward comment="TORRENT No 3: Drop outgoing TCP announce" content="info_hash=" disabled=no dst-port=2710,80,443 protocol=tcp

#Enable NAT for Web Translation (Should not have ETH1 and ETH2 bridged, use NAT to get your LAN to the WAN connection)
/ip firewall nat
add action=masquerade chain=srcnat out-interface=ether1

#Detect Compromised Hosts (SMTP Outbound and NetBIOS Outbound)
add action=drop chain=forward comment="Log and Drop potential compromised internal hosts" log=yes log-prefix=SMTP-25-VIOLATION out-interface=ether1 port=25 protocol=tcp
add action=drop chain=forward comment="Log and Drop Netbios/SMB outbound" dst-port=139 log=yes log-prefix=NETBIOS-139-VIOLATION out-interface=ether1 protocol=tcp
add action=drop chain=forward dst-port=445 log=yes log-prefix=NETBIOS-445-VIOLATION out-interface=ether1 protocol=tcp