A script to set up WAN/LAN/WLAN to get you started

From MikroTik Wiki
Revision as of 16:15, 17 September 2009 by Vitell (talk | contribs) (Bug fixes.)
Jump to: navigation, search

The Explanation

TBC

The Complete Script

#
# Basic ROS config
# Save this file as 'configscript.rsc' and drag it to the files window.
# At the command line, type '/import configscript.rsc' and read the
# logs!
#
# 20090915 - Nick Barnes - www.vitell.co.uk
# No rights reserved. Tinker to your heart's desire.
#
#################################################################
#
# The purpose of this script is to create a standard SOHO type
# configuration which can be built on by the user.
# It does not provide a complete solution, but should be enough
# to get you up and running.
#
#################################################################
# WARNING
# As this script stands, it will trash your existing configuration
# so don't run it on a router which has been customised or it won't
# be any more!
#
# DO NOT run this on a live production system.
#
# We accept absolutely no liability whatsoever. If you choose to run
# this script, anything bad that happens is entirely your problem.
# Of course, if you're happy, please let us know!!
#
# We recommend that your configuration be cleared with the command
# '/system routerboard reset-configuration'
# before this script is run.
#################################################################
#
# Make your changes here:
##########################
# Changes should be made to the text inside the speechmarks, for example....
# :local variablename "contents"
# should NOT be changed to
# :local myvariablename "contents"
# as this will crash everything!!
# Instead, you should put
# :local variablename "mycontents"
# or somesuch.
#
#
# Secure your RouterOS! Set the password you would like to use when logging on as 'admin'.
:local adminpassword "Password";
#
#
# Time servers (NTP).
# We use two NTP servers and these must be specified as FQDNs
# (Fully qualified domain names) - i.e. not IP addresss.
# Note that NTP we cannot assume that at the time configuration is run you will have an Internet
# connection and so we cannot set this up with the addresses you choose immediately (if we try to
# but RouterOS cannot resolve the host names, the script will crash). So we set up dummy IP addresses
# to start with and then configure a script to run regularly to ensure that
# the following addresses are used once the Internet connection is up. This sounds long and
# complicated, but it's actually a better way of doing things anyway - it means that if the IP
# addresses change for these hosts (as they will do if you use the pool.ntp.org addresses), your
# RouterOS will always be connected to a working server.
# The defaults are fine, but you may want to change one of the servers to point at your ISPs
# service if they run one.
:local ntpa "0.uk.pool.ntp.org";
:local ntpb "1.uk.pool.ntp.org";
# Now we define the temporary IP addresses to use pending resolution of the FQDNs above.
# You can probably leave them at the defaults, but this may mean that your ROS doesn't get
# the correct time for an hour or so. Note that once it has the correct time, it'll keep those
# IPs, so after a reboot, time syncing should be really quick.
:local ntptempa "81.187.81.101";
:local ntptempb "81.187.81.101";
#
#
# Set up mail defaults
# The 'emailserver' must be a FQDN and this setting works in the same way as the NTP servers above
# (i.e. we cannot assume that we can resolve the name right now)
:local emailserver "your.smtp.smarthost.com";
# Again, in the same way we did for NTP, above, we'll use the following IP address until we
# can resolve the FQDN specified above. You're OK leaving this as the default, but doing so
# may mean that e-mail doesn't work until the FQDN can be resolved.
:local emailservertempip "81.187.30.51";
#
# The default address e-mails will appear to have been sent from.
:local emailfrom "RouterBoard <routeros.email@address>";
#
# The e-mail address which should be notified about things happening on this system.
:local emailto "your.email@address";
#
#
# Name servers must be IP addresses (i.e. not a FQDN)
:local nsa "208.67.222.222";
:local nsb "208.67.220.220";
#
#
# Use NAT (yes/no) - Set to 'yes' unless you know what you're doing!
:local natuse "yes";
#
#
# Use PPPoE (yes/no) - Set to 'no' unless you know what you're doing!
:local pppoeuse "no";
#
#
# Offer NTP to LAN (yes/no) - Leave this as 'no' unless you have installed the NTP package.
# This sets the system up as a NTP server. This probably isn't necessary for simple solutions
# but can save a lot of bandwidth for larger systems
:local ntpserver "no";
#
#
# Your PPPoE login details (ignored if PPPoE is not used)
# PPPoE is configured on the WAN interface in addition to the WAN IP addresses defined below.
#
# Username
:local pppoeuser "user@a.1";
# Password
:local pppoepassword "mypassword";
# The IP address you expect to have allocated to this interface.
# Set to empty ("") if your address is allocated dynamically.
# This is used to determine whether the link has gone down and you
# have been allocated an incorrect IP address (typically this would
# be when you have BT broadband in the UK!)
# Leaving this variable blank means that a monitoring script will not
# be created.
:local pppoeipaddress "";
#
#
# Interfaces
# You may define one WAN interface
# You may define an ethernet LAN interface and/or a wireless LAN interface
# If you want both ethernet and wireless, a bridge is created across
# the two interfaces.
# Do we want to have our LAN on Ethernet (yes/no)
:local useetherlan "yes";
# Do we want to have our LAN on Wireless (yes/no)
:local usewlan "no";
# WAN interface
:local waninterface "wlan1";
# Ethernet LAN interface
:local etherlaninterface "ether1";
# Wireless LAN interface
:local wlaninterface "wlan1";
# Name of bridge to create if both useetherlan and usewlan are 'yes'
# You can safely leave this alone.
:local bridgeinterface "bridge1";
# Name of PPPoE interface to create if pppoeuse is 'yes'
# You can safely leave this alone.
:local pppoeinterface "MyPPPoE";
#
#
# WAN and LAN IP addresses and bits
# The WAN address to use, the network it's in and the number of bits in the subnet mask.
# These are NOT checked!! Note that even if you are using PPPoE, you will still want to
# define a WAN network so you can browse the web pages of your ADSL modem!
:local wanaddress "1.1.1.1";
:local wannetwork "1.1.1.0";
:local wanbits "30";
# And the same for the LAN address
:local lanaddress "192.168.42.111";
:local lannetwork "192.168.42.0";
:local lanbits "24";
#
#
# Define the gateway
# If we are using PPPoE, this is not used, otherwise it's our route out to the world
# and should probably be the address of your ADSL modem/router.
:local wangateway "1.1.1.2";
#
#
# Wireless configuration
# This is only used if usewlan, above is "yes"
# If you want a wireless LAN, this script sets one up with WPA and WPA2 security.
# Define the frequency we want to run on. We suggest you leave this at the default and tweak it
# later if required.
:local wlanfreq "2412";
# Your SSID
:local wlanssid "MySSID";
# The Key to use.
:local wlankey "ChangeMePlease";
#
#
# Act as DHCP server to LAN (yes/no)
:local dhcpuse "no";
# Define the start and end addresses of the pool to offer.
:local dhcppoolstart "192.168.0.2";
:local dhcppoolend "192.168.0.254";
# If required, define the domain. You can probably leave this as the default.
:local dhcpdomain "";
#
#
# Set failsafe access (yes/no)
# Add rule to firewall to allow full and complete access from your LAN to your ROS system?
# There's probably no harm in this (assuming you've got passwords set wherever you need them)
# especially since your LAN IPs are granted access anyway, but if you want it, you
# must turn it on here
:local fwallallowlan "yes";
#
################################################################
# Don't change anything below this line. Please!
################################################################
#
#
# Set up logging so we get more than the standard 100 lines.
/system logging action set memory memory-lines=500
#
:log info "Starting pre-flight checks";
#
:local failedtests "0";
#
# Check that if we're using an ethernet LAN, the interface defined exists.
:if ($useetherlan = "yes" and [/interface find name=$etherlaninterface] = "") do={
    :log error "Specified Ethernet LAN interface '$etherlaninterface' doesn't exist.";
	:set failedtests "1";
  }
# Check that if we're using a wireless LAN, we have the wireless package installed.
:if ($usewlan = "yes" and [/system package find name=wireless] = "") do={
    :log error "\$usewlan=\"yes\", but wireless package is not installed.";
	:set failedtests "1";
  }
# Check that if we're using a wireless LAN, the interface exists.
:if ($usewlan = "yes" and [/interface find name=$wlaninterface] = "") do={
    :log error "Specified Wireless LAN interface '$wlaninterface' doesn't exist.";
	:set failedtests "1";
  }
# Check that the WAN interface exists
:if ([/interface find name=$waninterface] = "") do={
    :log error "Specified WAN interface '$waninterface' doesn't exist.";
	:set failedtests "1";
  }
# Check that we aren't using the same interface for different purposes
:if ((($useetherlan = "yes") and ($usewlan = "yes") and ($etherlaninterface = $wlaninterface)) or \
  (($useetherlan = "yes") and ($etherlaninterface = $waninterface)) or \
  (($usewlan = "yes") and ($wlaninterface = $waninterface))) do={
    :log error "two or all of eLAN, wLAN and WAN interfaces are set to the same value";
	:set failedtests "1";
	}
# If we want PPPoE, we need the PPP package.
:if ($pppoeuse = "yes" and [/system package find name=ppp] = "") do={
    :log error "\$pppoeuse=\"yes\", but PPP package is not installed.";
	:set failedtests "1";
  }
# If we want to be a NTP server, we need the NTP package.
:if ($ntpserver = "yes" and [/system package find name=ntp] = "") do={
    :log error "\$ntpserver=\"yes\", but NTP package is not installed.";
	:set failedtests "1";
  }
#
# If we've failed any of the tests above, die!
:if ($failedtests != "0") do={
  :put "";
  :put "";
  :error "Script execution stopped under error condition. Please see the system log for details.";
  }
#
# Clearing out the garbage.
/system scheduler remove [find];
/interface bridge remove [find];
/interface bridge port remove [find];
/ip address remove [find];
/ip route remove [find dst-address=0.0.0.0/0];
/ip dhcp-server remove [find];
/ip pool remove [find];
/ip dhcp-server network remove [find];
/system script remove [find];
/ip firewall address-list remove [find];
/ip firewall nat remove [find];
/ip firewall filter remove [find];
#
# Set admin password
:log info "Setting admin password";
/user set admin password="$adminpassword";
#
# Configure e-mail
:log info "Configuring e-mail details";
/tool e-mail set from="$emailfrom" password="" server=("$emailservertempip" . ":25") username="";
#
#
# Get wireless working if required.
:if ($usewlan = "yes") do={
  :log info "Setting Wireless LAN security";
  /interface wireless reset-configuration $wlaninterface ;
  /interface wireless security-profiles remove [find name!=default];
  /interface wireless security-profiles add \
    authentication-types=wpa-psk,wpa2-psk,wpa-eap,wpa2-eap eap-methods=\
    passthrough group-ciphers=tkip,aes-ccm group-key-update=5m \
    interim-update=0s mode=dynamic-keys name=autoconfig \
	unicast-ciphers=tkip,aes-ccm \
	wpa-pre-shared-key=$wlankey wpa2-pre-shared-key=$wlankey;
  /interface wireless set $wlaninterface band=2.4ghz-b/g \
    default-authentication=yes default-forwarding=yes disabled=no \
    frequency=$wlanfreq mode=ap-bridge \
    security-profile=autoconfig \
    ssid=$wlanssid;
  }
#
#
# Work out which is the correct LAN interface to use...
# Essentially, if we're using etherLAN and wlan, we need to bridge the
# two together.
:local internalinterface;
:if ($useetherlan = "yes") do={
  :if ($usewlan = "yes") do={
    :set internalinterface "$bridgeinterface";
    } else={
	:set internalinterface "$etherlaninterface";
	}
  } else={
  :if ($usewlan = "yes") do={
    :set internalinterface "$wlaninterface";
    } else={
	:set internalinterface "$bridgeinterface";
	}
  }
#
# Set up the bridge and add the interfaces if required.
:if ($internalinterface = $bridgeinterface) do={
  /interface bridge add admin-mac=00:00:00:00:00:00 ageing-time=5m arp=enabled auto-mac=yes \
    comment="Automatic" disabled=no forward-delay=15s l2mtu=65535 max-message-age=20s \
    mtu=1500 name=$bridgeinterface priority=0x8000 protocol-mode=none \
    transmit-hold-count=6;
  /interface bridge port add bridge=$bridgeinterface comment="Automatic" disabled=no edge=auto external-fdb=auto \
    horizon=none interface=$etherlaninterface path-cost=10 point-to-point=auto priority=0x80
  /interface bridge port add bridge=$bridgeinterface comment="Automatic" disabled=no edge=auto external-fdb=auto \
    horizon=none interface=$wlaninterface path-cost=10 point-to-point=auto priority=0x80
  }
#
:log info "Using $internalinterface as the internal interface.";
#
#
# Set up interfaces with the correct addresses
:log info "Setting WAN IP address to $wanaddress/$wanbits on interface $waninterface";
/ip address add address="$wanaddress/$wanbits" comment="WAN" disabled=no interface=$waninterface;
:log info "Setting LAN IP address to $lanaddress/$lanbits on interface $internalinterface";
/ip address add address="$lanaddress/$lanbits" comment="LAN" disabled=no interface=$internalinterface;
#
#
# Sort out gateway
:if ($pppoeuse != "yes") do={
  :log info "Setting gateway to $wangateway";
  /ip route add comment="Default route" disabled=no distance=1 dst-address=0.0.0.0/0 gateway=$wangateway;
} else={
  :log info "Not setting gateway as this will be provided by PPPoE.";
}
#
#
# And DNS
:log info "Setting DNS servers to $nsa and $nsb"
/ip dns set allow-remote-requests=yes cache-max-ttl=1w cache-size=2048KiB \
    max-udp-packet-size=512 primary-dns=$nsa secondary-dns=$nsb
#
#
# Set up DHCP server if required
:if ($dhcpuse = "yes") do={
  :log info "Setting DHCP server on interface $internalinterface, pool $dhcppoolstart-$dhcppoolend";
  /ip pool add name=DHCPpool ranges="$dhcppoolstart-$dhcppoolend";
  /ip dhcp-server network add address="$lannetwork/$lanbits" comment="DHCP" \
    dns-server="$nsa,$nsb" domain=$dhcpdomain;
  /ip dhcp-server add address-pool=DHCPpool authoritative=yes disabled=no \
    interface=$internalinterface lease-time=3d name=DHCPserver;
} else={
  :log info "Skipping DHCP server configuration.";
}
#
#
# Set up PPPoE if required
:if ($pppoeuse = "yes") do={
  /interface pppoe-client remove [find];
  :log info "Setting up PPPoE";
  /interface pppoe-client add add-default-route=yes allow=chap comment="PPPoE" \
    dial-on-demand=no disabled=no interface=$waninterface max-mru=1480 max-mtu=1480 \
    mrru=disabled name="$pppoeinterface" password=$pppoepassword profile=default \
    service-name="" use-peer-dns=no user=$pppoeuser;
  } else={
    :log info "Skipping PPPoE configuration.";
  }
#
#
# Set up NTP client (doesn't matter what addresses we specify here as long as there's something there)
:log info "Setting up NTP client with dummy addresses.";
/system ntp client set enabled=yes mode=unicast primary-ntp="$ntptempa" secondary-ntp="$ntptempb";
:log info "Creating script to update with NTP servers $ntpa and $ntpb";
/system script add name=setntpip policy=ftp,write,winbox source="# Resolve the two ntp hostnames\r\
    \n:local ntpipa [:resolve \"$ntpa\"];\r\
    \n:local ntpipb [:resolve \"$ntpb\"];\r\
    \n/system ntp client set primary-ntp=\"\$ntpipa\" secondary-ntp=\"\$ntpipb\";";
:log info "Scheduling script.";
/system scheduler add comment="Set the correct NTP addresses" disabled=no interval=1h name=setntpservers on-event=setntpip \
    policy=write,test start-date=jan/01/1970 start-time=12:34:56;
:log info "Running script on the offchance all interfaces are set up and it will work."
:execute setntpip;
#
#
# Set up as NTP server
:if ($ntpserver = "yes") do={
  :log info "Setting up NTP server";
  /system ntp server set broadcast=no enabled=yes manycast=yes multicast=no;
  } else={
    :log info "Skipping NTP server configuration.";
  }
#
#
# Start with the firewall stuff.
# First, define local addresses.
:log info "Adding $lannetwork/$lanbits to local address list.";
/ip firewall address-list add address="$lannetwork/$lanbits" comment="LAN" disabled=no list=local
#
#
# Set up NAT if required. We need to know which interface to use (PPPoE or WAN)
:local natinterface;
:if ($natuse = "yes") do={
  :if ($pppoeuse = "yes") do={
    :log info "Using PPPoE interface for NAT";
    :set natinterface "$pppoeinterface";
  } else={
    :log info "Using WAN interface for NAT";
    :set natinterface "$waninterface";
  }
  :log info "NATting to interface $natinterface";
  /ip firewall nat add action=masquerade chain=srcnat comment="NAT" disabled=no out-interface="$natinterface"
} else={
  :log info "Skipping NAT configuration.";
}
#
#
# Add filter rules
/ip firewall filter
:log info "Setting filters";
add action=accept chain=input comment="Local access to RB for Winbox" \
    disabled=no dst-port=8291 protocol=tcp src-address-list=local
# Failsafe access
:if ($fwallallowlan = "yes") do={
  :if ($useetherlan = "yes") do={
    add action=accept chain=input comment="eLAN" disabled=no in-interface="$etherlaninterface";
	}
  :if ($usewlan = "yes") do={
    add action=accept chain=input comment="wLAN" disabled=no in-interface="$wlaninterface";
	}
  :if (($useetherlan = "yes") and ($usewlan = "yes")) do={
    add action=accept chain=input comment="bridge" disabled=no in-interface="$bridgeinterface";
	}
  }
#
add action=jump chain=input comment="Treat all traffic equally" \
    disabled=no jump-target=inbound
add action=jump chain=forward comment="Treat all traffic equally" disabled=no jump-target=inbound
add action=drop chain=inbound comment="Drop invalid" connection-state=invalid \
    disabled=no
add action=accept chain=inbound comment="Allow limited icmp" disabled=no \
    limit=50/5s,2 protocol=icmp
add action=drop chain=inbound comment="Drop excess icmp" disabled=no \
    protocol=icmp
add action=accept chain=inbound comment="Accept established" \
    connection-state=established disabled=no
add action=accept chain=inbound comment="Accept related" connection-state=\
    related disabled=no
add action=accept chain=inbound comment=\
    "Internal traffic can do what it wants." disabled=no src-address-list=\
    local
add action=drop chain=inbound comment="And drop everything else" disabled=no
add action=accept chain=output comment="Allow everything out" disabled=no
#
#
# Now to add some useful scripts
/system script
# Configure scripts
:log info "Creating automatic mail server setting script";
/system script add name=setmail policy=ftp,write,winbox source="# Resolve the mail server hostname\r\
  \n:local emailserverip [:resolve \"$emailserver\"];\r\
  \n/tool e-mail set server=\"\$emailserverip\";"
:log info "Scheduling automatic mail server setting script to run hourly.";
/system scheduler add comment="Set the correct mail server addresses" disabled=no interval=1h name=setmailserver on-event=setmail \
    policy=reboot,read,write,policy,test,password,sniff,sensitive start-date=jan/01/1970 start-time=12:34:56;
:log info "Running script on the offchance all interfaces are set up and it will work."
:execute setmail;
#
# Automatic backup
:log info "Creating automatic backup script";
/system script add name=makebackup policy=ftp,reboot,read,write,policy,test,winbox,password,sniff,sensitive source="\r\
    \n:log info \"Starting Backup Script\";\r\
    \n:local SYSname [/system identity get name];\r\
    \n:put \"\$SYSname\";\r\
    \n/export file=\"\$SYSname\";\r\
    \n:log info \"Finished exporting configuration\";\r\
    \n/tool e-mail send to=\"$emailto\" subject=(\$SYSname . \" backup\") file=(\$SYSname . \".rsc\");\r\
	\n:delay 10s;\r\
    \n/file remove (\$SYSname . \".rsc\");\r\
    \n:log info \"Finished Backup Script\"";
:log info "Scheduling automatic backup script to run weekly.";
/system scheduler add comment="Set the correct mail server addresses" disabled=no interval=7d name=runbackup on-event=makebackup \
    policy=reboot,read,write,policy,test,password,sniff,sensitive start-date=jan/01/1970 start-time=12:34:56;
#
# System startup notification
:log info "Creating system startup notification script";
/system script add name=Systemstartupnotification policy=ftp,reboot,read,write,policy,test,winbox,sniff source="\r\
    \n:local date ([:pick [/system clock get date] 7 11] . [:pick [/system clock get date] 0 3] . [:pick [/system clock get date] 4 6]);\r\
    \n\r\
    \n:log info \"Running system startup script\";\r\
    \n\r\
    \n:local filename ([/system identity get name] . \"Log-\" . \$date);\r\
    \n:local fullfilename (\$filename . \".txt\");\r\
    \n\r\
    \n/log print file=\$fullfilename;\r\
    \n\r\
    \n/tool e-mail send to=\"$emailto\" subject=(\"Routerboard reboot - \" . \$filename) file=\$filename \\\r\
	\n  body=\"RouterOS was restarted (RB rebooted?). Recent logs attached.\";\r\
    \n\r\
    \n:delay 10s;\r\
    \n\r\
    \n/file remove \$fullfilename;\r\
    \n\r\
    \n:log info (\"System Log emailed at \" . [/system clock get time] . \" \" . \$date);\r\
    \n";
:log info "Scheduling system startup notification script to run on startup.";
/system scheduler add comment="We've been rebooted" disabled=no interval=0s name=reboot on-event=Systemstartupnotification \
    policy=reboot,read,write,policy,test,password,sniff,sensitive start-time=startup;
#
#
# Restart PPPoE if the IP address isn't what we expect
:if ($pppoeuse = "yes" and $pppoeipaddress != "") do={
/system script add name=checkpppoe policy=ftp,reboot,read,write,policy,test,winbox,password,sniff,sensitive source="\r\
    \n# Define the following two\r\
    \n#\r\
    \n# Name of the PPPoE interface\r\
    \n:local pppoeint \"$pppoeinterface\";\r\
    \n:local expectedip \"$pppoeipaddress/32\";\r\
    \n\r\
    \n:local curip [/ip address get [find interface=\$pppoeint] address];\r\
    \n\r\
    \n:if (\$curip != \$expectedip) do={\r\
    \n  /interface disable \"\$pppoeint\";\r\
    \n  :delay 1s;\r\
    \n  /interface enable \"\$pppoeint\";\r\
    \n}\r\
    \n\r\
    \n"
/system scheduler add comment="Check PPPoE" disabled=no interval=2m name=checkpppoe on-event=checkpppoe \
    policy=reboot,read,write,policy,test,password,sniff,sensitive start-date=jan/01/1970 start-time=12:34:56;
}
#
:log info "Auto configuration ended.";
:put "";
:put "Auto configuration ended. Please check the system log.";
:put "";