Merge remote-tracking branch 'refs/remotes/pi-hole/development' into development

This commit is contained in:
Daniel (Fourdee) 2016-08-12 12:11:55 +01:00
commit 7e5bcd2ec3
30 changed files with 2076 additions and 590 deletions

7
.github/ISSUE_TEMPLATE.md vendored Normal file
View file

@ -0,0 +1,7 @@
##### Expected Behaviour:
##### Actual Behaviour:
##### Steps to reproduce this issue:

11
.github/PULL_REQUEST_TEMPLATE.md vendored Normal file
View file

@ -0,0 +1,11 @@
Fixes #[issue number] .
Changes proposed in this pull request:
-
-
-
@pi-hole/gravity

1
.gitignore vendored Normal file
View file

@ -0,0 +1 @@
.DS_Store

14
.pullapprove.yml Normal file
View file

@ -0,0 +1,14 @@
approve_by_comment: true
approve_regex: '^(Approved|:shipit:|:\+1:)'
reject_regex: '^(Rejected|:-1:)'
reset_on_push: true
author_approval: required
reviewers:
members:
- brantje
- dschaper
- jacobsalmela
- Mcat12
- PromoFaux
name: pullapprove
required: 3

8
CONTRIBUTING.md Normal file
View file

@ -0,0 +1,8 @@
This is a basic checklist for now, We will update it in the future.
* Fork the repo and create your new branch based on the `development` branch.
* Commit Unix line endings
* If you want, try to keep to the theme of black holes/gravity. This can add some fun to your submission.
* Submit Pull Requests to the development branch only.
* Before Submitting your Pull Request, merge `development` with your new branch and fix any conflicts. (Make sure you don't break anything in development!)
* Be patient. We will review all submitted pull requests, but our focus is on stability.. please don't be offended if we reject your PR, or it appears we're doing nothing with it! We'll get around to it..

147
README.md
View file

@ -1,87 +1,124 @@
# Automated Install [![Bountysource](https://www.bountysource.com/badge/tracker?tracker_id=3011939)](https://www.bountysource.com/trackers/3011939-pi-hole-pi-hole?utm_source=3011939&utm_medium=shield&utm_campaign=TRACKER_BADGE)
##### Designed For Raspberry Pi B, B+, 2, and Zero (with an Ethernet adapter)
1. Install Raspbian # Automated Install
2. Run the command below
### ```curl -L install.pi-hole.net | bash``` Designed For Raspberry Pi A+, B, B+, 2, 3B, and Zero (with an Ethernet/Wi-Fi adapter)
Works on most Debian and CentOS/RHEL based distributions!
Once installed, [configure your router to have **DHCP clients use the Pi as their DNS server**](http://pi-hole.net/faq/can-i-set-the-pi-hole-to-be-the-dns-server-at-my-router-so-i-dont-have-to-change-settings-for-my-devices/) and then any device that connects to your network will have ads blocked without any further configuration. Alternatively, you can manually set each device to [use the Raspberry Pi as its DNS server](http://pi-hole.net/faq/how-do-i-use-the-pi-hole-as-my-dns-server/). 1. Install Raspbian
2. Run the command below (downloads [this script](https://github.com/pi-hole/pi-hole/blob/master/automated%20install/basic-install.sh) in case you want to read over it first!)
## Pi-hole Is Free, But Powered By Your Donations ## `curl -L https://install.pi-hole.net | bash`
[![Donate](https://www.paypalobjects.com/en_US/i/btn/btn_donateCC_LG.gif "Free, but powered by donations")](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=3J2L3Z4DHW9UY "Donate")
### Alternative Semi-Automated install
```bash
wget -O basic-install.sh https://install.pi-hole.net
chmod +x basic-install.sh
./basic-install.sh
```
If you wish to read over the script before running it, then after the `wget` command, do `nano basic-install.sh` to open a text viewer
Once installed, [configure your router to have **DHCP clients use the Pi as their DNS server**](http://pi-hole.net/faq/can-i-set-the-pi-hole-to-be-the-dns-server-at-my-router-so-i-dont-have-to-change-settings-for-my-devices/) and then any device that connects to your network will have ads blocked without any further configuration. Alternatively, you can manually set each device to [use the Raspberry Pi as its DNS server](http://pi-hole.net/faq/how-do-i-use-the-pi-hole-as-my-dns-server/).
## How To Install Pi-hole
[![60-second install tutorial](http://i.imgur.com/5TEc3a6.png)](https://www.youtube.com/watch?v=TzFLJqUeirA)
## How It Works
## How Does It Work?
**Watch the 60-second video below to get a quick overview** **Watch the 60-second video below to get a quick overview**
[![Pi-hole exlplained](http://i.imgur.com/qNybJDX.png)](https://vimeo.com/135965232) [![Pi-hole exlplained](http://i.imgur.com/pG1m937.png)](https://youtu.be/9Eti3xibiho)
## Pi-hole Projects ## Pi-hole Is Free, But Powered By Your Donations
- [Pi-hole Chrome extension](https://chrome.google.com/webstore/detail/pi-hole-list-editor/hlnoeoejkllgkjbnnnhfolapllcnaglh) ([open source](https://github.com/packtloss/pihole-extension))
- [Go Bananas for CHiP-hole ad blocking](https://www.hackster.io/jacobsalmela/chip-hole-network-wide-ad-blocker-98e037)
- [Sky-Hole](http://dlaa.me/blog/post/skyhole)
- [Pi-hole in the Cloud!](http://blog.codybunch.com/2015/07/28/Pi-Hole-in-the-cloud/)
- [unRaid-hole](https://github.com/spants/unraidtemplates/blob/master/Spants/unRaid-hole.xml#L13)--[Repo and more info](http://lime-technology.com/forum/index.php?PHPSESSID=c0eae3e5ef7e521f7866034a3336489d&topic=38486.0)
- [Pi-hole on/off button](http://thetimmy.silvernight.org/pages/endisbutton/)
- [Minibian Pi-hole](http://munkjensen.net/wiki/index.php/See_my_Pi-Hole#Minibian_Pi-hole)
## Coverage Send a one-time donation or sign up for Optimal.com's service using our link below to provide us with a small portion of the monthly fee.
- [Splunk: Pi-hole Visualizser](https://splunkbase.splunk.com/app/3023/)
- [The Defrag Show - MSDN/Channel 9](https://channel9.msdn.com/Shows/The-Defrag-Show/Defrag-Endoscope-USB-Camera-The-Final-HoloLens-Vote-Adblock-Pi-and-more?WT.mc_id=dlvr_twitter_ch9#time=20m39s)
- [MacObserver Podcast 585](http://www.macobserver.com/tmo/podcast/macgeekgab-585)
- [Medium: Block All Ads For $53](https://medium.com/@robleathern/block-ads-on-all-home-devices-for-53-18-a5f1ec139693#.gj1xpgr5d)
- [MakeUseOf: Adblock Everywhere, The Pi-hole Way](http://www.makeuseof.com/tag/adblock-everywhere-raspberry-pi-hole-way/)
- [Lifehacker: Turn Your Pi Into An Ad Blocker With A Single Command](http://lifehacker.com/turn-a-raspberry-pi-into-an-ad-blocker-with-a-single-co-1686093533)!
- [Pi-hole on TekThing](https://youtu.be/8Co59HU2gY0?t=2m)
- [Pi-hole on Security Now! Podcast](http://www.youtube.com/watch?v=p7-osq_y8i8&t=100m26s)
- [Foolish Tech Show](https://youtu.be/bYyena0I9yc?t=2m4s)
- [Pi-hole on Ubuntu](http://www.boyter.org/2015/12/pi-hole-ubuntu-14-04/)
- [Catchpoint: iOS 9 Ad Blocking](http://blog.catchpoint.com/2015/09/14/ad-blocking-apple/)
## Partnering With Optimal.com - ![Paypal](http://i.imgur.com/3muNfxu.png) : [Donate](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=3J2L3Z4DHW9UY)
- ![Flattr](http://i.imgur.com/ZFceFRu.png) : [Donate](https://flattr.com/submit/auto?user_id=jacobsalmela&url=https://github.com/pi-hole/pi-hole)
- ![Bitcoin](http://i.imgur.com/FIlmOMG.png) : 1GKnevUnVaQM2pQieMyeHkpr8DXfkpfAtL
Pi-hole will be teaming up with [Rob Leathern's subscription service to avoid ads](https://medium.com/@robleathern/block-ads-on-all-home-devices-for-53-18-a5f1ec139693#.gj1xpgr5d). This service is unique and will help content-creators and publishers [still make money from visitors who are using an ad ablocker](http://techcrunch.com/2015/12/17/the-new-optimal/). ## Get Help Or Connect With Us On The Web
- [@The_Pi_Hole](https://twitter.com/The_Pi_Hole)
- [/r/pihole](https://www.reddit.com/r/pihole/)
- [Pi-hole YouTube channel](https://www.youtube.com/channel/UCT5kq9w0wSjogzJb81C9U0w)
- [Wiki](https://github.com/pi-hole/pi-hole/wiki/Customization)
- [FAQs](https://pi-hole.net/help/)
- [![Join the chat at https://gitter.im/pi-hole/pi-hole](https://badges.gitter.im/pi-hole/pi-hole.svg)](https://gitter.im/pi-hole/pi-hole?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
## Technical Details ## Technical Details
The Pi-hole is an **advertising-aware DNS/Web server**. If an ad domain is queried, a small Web page or GIF is delivered in place of the advertisement. You can also [replace ads with any image you want](http://pi-hole.net/faq/is-it-possible-to-change-the-blank-page-that-takes-place-of-the-ads-to-something-else/) since it is just a simple Webpage taking place of the ads. The Pi-hole is an **advertising-aware DNS/Web server**. If an ad domain is queried, a small Web page or GIF is delivered in place of the advertisement. You can also [replace ads with any image you want](http://pi-hole.net/faq/is-it-possible-to-change-the-blank-page-that-takes-place-of-the-ads-to-something-else/) since it is just a simple Webpage taking place of the ads.
A more detailed explanation of the installation can be found [here](http://jacobsalmela.com/block-millions-ads-network-wide-with-a-raspberry-pi-hole-2-0). ### Gravity
## Gravity The [gravity.sh](https://github.com/pi-hole/pi-hole/blob/master/gravity.sh) does most of the magic. The script pulls in ad domains from many sources and compiles them into a single list of [over 1.6 million entries](http://jacobsalmela.com/block-millions-ads-network-wide-with-a-raspberry-pi-hole-2-0) (if you decide to use the [mahakala list](https://github.com/pi-hole/pi-hole/commit/963eacfe0537a7abddf30441c754c67ca1e40965)).
The [gravity.sh](https://github.com/pi-hole/pi-hole/blob/master/gravity.sh) does most of the magic. The script pulls in ad domains from many sources and compiles them into a single list of [over 1.6 million entries](http://jacobsalmela.com/block-millions-ads-network-wide-with-a-raspberry-pi-hole-2-0) (if you decide to use the [mahakala list](https://github.com/pi-hole/pi-hole/commit/963eacfe0537a7abddf30441c754c67ca1e40965)).
## Whitelist and blacklist
Domains can be whitelisted and blacklisted using two pre-installed scripts. See [the wiki page](https://github.com/pi-hole/pi-hole/wiki/Whitelisting-and-Blacklisting) for more details
## Web Interface ## Web Interface
The [Web interface](https://github.com/jacobsalmela/AdminLTE#pi-hole-admin-dashboard) will be installed automatically so you can view stats and change settings. You can find it at:
`http://192.168.1.x/admin/index.php` The [Web interface](https://github.com/jacobsalmela/AdminLTE#pi-hole-admin-dashboard) will be installed automatically so you can view stats and change settings. You can find it at:
### API `http://192.168.1.x/admin/index.php` or `http://pi.hole/admin`
![Pi-hole Advanced Stats Dashboard](http://i.imgur.com/gTq2GbS.png)
### Whitelist and blacklist
Domains can be whitelisted and blacklisted using two pre-installed scripts. See [the wiki page](https://github.com/pi-hole/pi-hole/wiki/Whitelisting-and-Blacklisting) for more details ![Whitelist editor in the Web interface](http://i.imgur.com/ogu2ewg.png)
## API
A basic read-only API can be accessed at `/admin/api.php`. It returns the following JSON: A basic read-only API can be accessed at `/admin/api.php`. It returns the following JSON:
```JSON
```json
{ {
"domains_being_blocked": "136708", "domains_being_blocked": "136708",
"dns_queries_today": "18108", "dns_queries_today": "18108",
"ads_blocked_today": "14648", "ads_blocked_today": "14648",
"ads_percentage_today": "80.89" "ads_percentage_today": "80.89"
} }
``` ```
The same output can be acheived on the CLI by running `chronometer.sh -j`
![Web](http://i.imgur.com/m114SCn.png) The same output can be achieved on the CLI by running `chronometer.sh -j`
## Real-time Statistics ## Real-time Statistics
You can view [real-time stats](http://pi-hole.net/faq/install-the-real-time-lcd-monitor-chronometer/) via `ssh` or on an [2.8" LCD screen](http://amzn.to/1P0q1Fj). This is accomplished via [`chronometer.sh`](https://github.com/pi-hole/pi-hole/blob/master/advanced/Scripts/chronometer.sh). You can view [real-time stats](http://pi-hole.net/faq/install-the-real-time-lcd-monitor-chronometer/) via `ssh` or on an [2.8" LCD screen](http://amzn.to/1P0q1Fj). This is accomplished via [`chronometer.sh`](https://github.com/pi-hole/pi-hole/blob/master/advanced/Scripts/chronometer.sh). ![Pi-hole LCD](http://i.imgur.com/nBEqycp.jpg)
![Pi-hole LCD](http://i.imgur.com/nBEqycp.jpg)
## Help ## Pi-hole Projects
- See the [Wiki](https://github.com/pi-hole/pi-hole/wiki/Customization) entry for more details
- There is also an [FAQ section on pi-hole.net](http://pi-hole.net) - [Pi-hole stats in your Mac's menu bar](https://getbitbar.com/plugins/Network/pi-hole.1m.py)
- [Get LED alerts for each blocked ad](http://www.stinebaugh.info/get-led-alerts-for-each-blocked-ad-using-pi-hole/)
- [Pi-hole on Ubuntu 14.04 on VirtualBox](http://hbalagtas.blogspot.com/2016/02/adblocking-with-pi-hole-and-ubuntu-1404.html)
- [x86 Docker container that runs Pi-hole](https://hub.docker.com/r/diginc/pi-hole/)
- [Splunk: Pi-hole Visualizser](https://splunkbase.splunk.com/app/3023/)
- [Pi-hole Chrome extension](https://chrome.google.com/webstore/detail/pi-hole-list-editor/hlnoeoejkllgkjbnnnhfolapllcnaglh) ([open source](https://github.com/packtloss/pihole-extension))
- [Go Bananas for CHiP-hole ad blocking](https://www.hackster.io/jacobsalmela/chip-hole-network-wide-ad-blocker-98e037)
- [Sky-Hole](http://dlaa.me/blog/post/skyhole)
- [Pi-hole in the Cloud!](http://blog.codybunch.com/2015/07/28/Pi-Hole-in-the-cloud/)
- [unRaid-hole](https://github.com/spants/unraidtemplates/blob/master/Spants/unRaid-hole.xml#L13)--[Repo and more info](http://lime-technology.com/forum/index.php?PHPSESSID=c0eae3e5ef7e521f7866034a3336489d&topic=38486.0)
- [Pi-hole on/off button](http://thetimmy.silvernight.org/pages/endisbutton/)
- [Minibian Pi-hole](http://munkjensen.net/wiki/index.php/See_my_Pi-Hole#Minibian_Pi-hole)
## Coverage
- [Adafruit livestream install](https://www.youtube.com/watch?v=eg4u2j1HYlI)
- [TekThing: 5 fun, easy projects for a Raspberry Pi](https://youtu.be/QwrKlyC2kdM?t=1m42s)
- [Pi-hole on Adafruit's blog](https://blog.adafruit.com/2016/03/04/pi-hole-is-a-black-hole-for-internet-ads-piday-raspberrypi-raspberry_pi/)
- [The Defrag Show - MSDN/Channel 9](https://channel9.msdn.com/Shows/The-Defrag-Show/Defrag-Endoscope-USB-Camera-The-Final-HoloLens-Vote-Adblock-Pi-and-more?WT.mc_id=dlvr_twitter_ch9#time=20m39s)
- [MacObserver Podcast 585](http://www.macobserver.com/tmo/podcast/macgeekgab-585)
- [Medium: Block All Ads For $53](https://medium.com/@robleathern/block-ads-on-all-home-devices-for-53-18-a5f1ec139693#.gj1xpgr5d)
- [MakeUseOf: Adblock Everywhere, The Pi-hole Way](http://www.makeuseof.com/tag/adblock-everywhere-raspberry-pi-hole-way/)
- [Lifehacker: Turn Your Pi Into An Ad Blocker With A Single Command](http://lifehacker.com/turn-a-raspberry-pi-into-an-ad-blocker-with-a-single-co-1686093533)!
- [Pi-hole on TekThing](https://youtu.be/8Co59HU2gY0?t=2m)
- [Pi-hole on Security Now! Podcast](http://www.youtube.com/watch?v=p7-osq_y8i8&t=100m26s)
- [Foolish Tech Show](https://youtu.be/bYyena0I9yc?t=2m4s)
- [Pi-hole on Ubuntu](http://www.boyter.org/2015/12/pi-hole-ubuntu-14-04/)
- [Catchpoint: iOS 9 Ad Blocking](http://blog.catchpoint.com/2015/09/14/ad-blocking-apple/)
## Other Operating Systems ## Other Operating Systems
This script will work for other UNIX-like systems with some slight **modifications**. As long as you can install `dnsmasq` and a Webserver, it should work OK. The automated install only works for a clean install of Raspiban right now since that is how the project originated.
This script will work for other UNIX-like systems with some slight **modifications**. As long as you can install `dnsmasq` and a Webserver, it should work OK. The automated install is only for a clean install of a Debian based system, such as the Raspberry Pi.

View file

@ -1,8 +1,57 @@
https://adaway.org/hosts.txt ## Pi-hole ad-list default sources. Updated 22/05/2016 #########################
# #
# To make changes to this file: #
# 1. run `cp /etc/pihole/adlists.default /etc/pihole/adlists.list` #
# 2. run `nano /etc/pihole/adlists.list` #
# 3. Uncomment or comment any of the below lists #
# #
# Know of any other lists? Feel free to let us know about them, or add them #
# to this file! #
################################################################################
# The below list amalgamates several lists we used previously.
# See `https://github.com/StevenBlack/hosts` for details
https://raw.githubusercontent.com/StevenBlack/hosts/master/hosts
# Other lists we consider safe:
http://adblock.gjtech.net/?format=unix-hosts http://adblock.gjtech.net/?format=unix-hosts
http://hosts-file.net/ad_servers.txt
http://www.malwaredomainlist.com/hostslist/hosts.txt
http://pgl.yoyo.org/adservers/serverlist.php?
http://someonewhocares.org/hosts/hosts
http://winhelp2002.mvps.org/hosts.txt
http://mirror1.malwaredomains.com/files/justdomains http://mirror1.malwaredomains.com/files/justdomains
http://sysctl.org/cameleon/hosts
https://zeustracker.abuse.ch/blocklist.php?download=domainblocklist
https://s3.amazonaws.com/lists.disconnect.me/simple_tracking.txt
https://s3.amazonaws.com/lists.disconnect.me/simple_ad.txt
# hosts-file.net list. Updated frequently, but has been known to block legitimate sites.
https://hosts-file.net/ad_servers.txt
# Mahakala list. Has been known to block legitimage domains including the entire .com range.
# Warning: Due to the sheer size of this list, the web admin console will be unresponsive.
#http://adblock.mahakala.is/
# ADZHOSTS list. Has been known to block legitimate domains
#http://optimate.dl.sourceforge.net/project/adzhosts/HOSTS.txt
# Windows 10 telemetry list
#https://raw.githubusercontent.com/crazy-max/WindowsSpyBlocker/master/data/hosts/win10/spy.txt
# Securemecca.com list - Also blocks "adult" sites (pornography/gambling etc)
#http://securemecca.com/Downloads/hosts.txt
# Quidsup's tracker list
https://raw.githubusercontent.com/quidsup/notrack/master/trackers.txt
# Block the BBC News website Breaking News banner
#https://raw.githubusercontent.com/BreakingTheNews/BreakingTheNews.github.io/master/hosts
# List of known C&C malware servers (see https://github.com/pi-hole/pi-hole/issues/528)
https://ransomwaretracker.abuse.ch/downloads/RW_DOMBL.txt
# Untested Lists:
#https://raw.githubusercontent.com/reek/anti-adblock-killer/master/anti-adblock-killer-filters.txt
#https://raw.githubusercontent.com/Dawsey21/Lists/master/main-blacklist.txt
#http://malwaredomains.lehigh.edu/files/domains.txt
# Following two lists should be used simultaneously: (readme https://github.com/notracking/hosts-blocklists/)
#https://raw.github.com/notracking/hosts-blocklists/master/hostnames.txt
#https://raw.github.com/notracking/hosts-blocklists/master/domains.txt
# Combination of serveral host files on the internet (warning some facebook domains are also blocked but you can go to facebook.com). See https://github.com/mat1th/Dns-add-block for more information.
#https://raw.githubusercontent.com/mat1th/Dns-add-block/master/hosts

185
advanced/Scripts/blacklist.sh Normal file → Executable file
View file

@ -10,54 +10,88 @@
# the Free Software Foundation, either version 2 of the License, or # the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version. # (at your option) any later version.
#rootcheck
if [[ $EUID -eq 0 ]];then
echo "::: You are root."
else
echo "::: sudo will be used."
# Check if it is actually installed
# If it isn't, exit because the install cannot complete
if [ -x "$(command -v sudo)" ];then
export SUDO="sudo"
else
echo "::: Please install sudo or run this script as root."
exit 1
fi
fi
function helpFunc()
{
echo "::: Immediately blacklists one or more domains in the hosts file"
echo ":::"
echo ":::"
echo "::: Usage: pihole -b domain1 [domain2 ...]"
echo "::: Options:"
echo "::: -d, --delmode Remove domains from the blacklist"
echo "::: -nr, --noreload Update blacklist without refreshing dnsmasq"
echo "::: -f, --force Force updating of the hosts files, even if there are no changes"
echo "::: -q, --quiet output is less verbose"
echo "::: -h, --help Show this help dialog"
echo "::: -l, --list Display your blacklisted domains"
exit 1
}
if [[ $# = 0 ]]; then if [[ $# = 0 ]]; then
echo "Immediately blacklists one or more domains in the hosts file" helpFunc
echo " "
echo "Usage: blacklist.sh domain1 [domain2 ...]"
echo " "
echo "Options:"
echo " -d, --delmode Remove domains from the blacklist"
echo " -nr, --noreload Update blacklist without refreshing dnsmasq"
echo " -f, --force Force updating of the hosts files, even if there are no changes"
echo " -q, --quiet output is less verbose"
exit 1
fi fi
#globals #globals
blacklist=/etc/pihole/blacklist.txt basename=pihole
adList=/etc/pihole/gravity.list piholeDir=/etc/$basename
adList=$piholeDir/gravity.list
blacklist=$piholeDir/blacklist.txt
reload=true reload=true
addmode=true addmode=true
force=false force=false
versbose=true verbose=true
domList=() domList=()
domToRemoveList=() domToRemoveList=()
piholeIPfile=/etc/pihole/piholeIP
piholeIPfile=/tmp/piholeIP
piholeIPv6file=/etc/pihole/.useIPv6 piholeIPv6file=/etc/pihole/.useIPv6
# Otherwise, the IP address can be taken directly from the machine, which will happen when the script is run by the user and not the installation script if [[ -f $piholeIPfile ]];then
IPv4dev=$(ip route get 8.8.8.8 | awk '{for(i=1;i<=NF;i++)if($i~/dev/)print $(i+1)}') # If the file exists, it means it was exported from the installation script and we should use that value instead of detecting it in this script
piholeIPCIDR=$(ip -o -f inet addr show dev $IPv4dev | awk '{print $4}' | awk 'END {print}') piholeIP=$(cat $piholeIPfile)
piholeIP=${piholeIPCIDR%/*} #rm $piholeIPfile
else
# Otherwise, the IP address can be taken directly from the machine, which will happen when the script is run by the user and not the installation script
IPv4dev=$(ip route get 8.8.8.8 | awk '{for(i=1;i<=NF;i++)if($i~/dev/)print $(i+1)}')
piholeIPCIDR=$(ip -o -f inet addr show dev "$IPv4dev" | awk '{print $4}' | awk 'END {print}')
piholeIP=${piholeIPCIDR%/*}
fi
modifyHost=false modifyHost=false
# After setting defaults, check if there's local overrides
if [[ -r $piholeDir/pihole.conf ]];then
echo "::: Local calibration requested..."
. $piholeDir/pihole.conf
fi
if [[ -f $piholeIPv6file ]];then if [[ -f $piholeIPv6file ]];then
# If the file exists, then the user previously chose to use IPv6 in the automated installer # If the file exists, then the user previously chose to use IPv6 in the automated installer
piholeIPv6=$(ip -6 route get 2001:4860:4860::8888 | awk -F " " '{ for(i=1;i<=NF;i++) if ($i == "src") print $(i+1) }') piholeIPv6=$(ip -6 route get 2001:4860:4860::8888 | awk -F " " '{ for(i=1;i<=NF;i++) if ($i == "src") print $(i+1) }')
fi fi
function HandleOther(){
function HandleOther(){
#check validity of domain #check validity of domain
validDomain=$(echo $1 | perl -ne'print if /\b((?=[a-z0-9-]{1,63}\.)(xn--)?[a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,63}\b/') validDomain=$(echo "$1" | perl -ne'print if /\b((?=[a-z0-9-]{1,63}\.)(xn--)?[a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,63}\b/')
if [ -z "$validDomain" ]; then if [ -z "$validDomain" ]; then
echo $1 is not a valid argument or domain name echo "::: $1 is not a valid argument or domain name"
else else
domList=("${domList[@]}" $validDomain) domList=("${domList[@]}" $validDomain)
fi fi
} }
@ -66,13 +100,12 @@ function PopBlacklistFile(){
#check blacklist file exists, and if not, create it #check blacklist file exists, and if not, create it
if [[ ! -f $blacklist ]];then if [[ ! -f $blacklist ]];then
touch $blacklist touch $blacklist
fi fi
for dom in "${domList[@]}" for dom in "${domList[@]}"; do
do if "$addmode"; then
if $addmode; then AddDomain "$dom"
AddDomain $dom
else else
RemoveDomain $dom RemoveDomain "$dom"
fi fi
done done
} }
@ -83,69 +116,66 @@ function AddDomain(){
grep -Ex -q "$1" $blacklist || bool=true grep -Ex -q "$1" $blacklist || bool=true
if $bool; then if $bool; then
#domain not found in the blacklist file, add it! #domain not found in the blacklist file, add it!
if $versbose; then if $verbose; then
echo -n "::: Adding $1 to blacklist file..." echo -n "::: Adding $1 to blacklist file..."
fi fi
echo $1 >> $blacklist echo "$1" >> $blacklist
modifyHost=true modifyHost=true
echo " done!" echo " done!"
else else
if $versbose; then if $verbose; then
echo "::: $1 already exists in blacklist.txt! No need to add" echo "::: $1 already exists in $blacklist! No need to add"
fi fi
fi fi
} }
function RemoveDomain(){ function RemoveDomain(){
bool=false bool=false
grep -Ex -q "$1" $blacklist || bool=true grep -Ex -q "$1" $blacklist || bool=true
if $bool; then if $bool; then
#Domain is not in the blacklist file, no need to Remove #Domain is not in the blacklist file, no need to Remove
if $versbose; then if $verbose; then
echo "::: $1 is NOT blacklisted! No need to remove" echo "::: $1 is NOT blacklisted! No need to remove"
fi fi
else else
#Domain is in the blacklist file, add to a temporary array #Domain is in the blacklist file, add to a temporary array
if $versbose; then if $verbose; then
echo "::: Un-blacklisting $dom..." echo "::: Un-blacklisting $dom..."
fi fi
domToRemoveList=("${domToRemoveList[@]}" $1) domToRemoveList=("${domToRemoveList[@]}" $1)
modifyHost=true modifyHost=true
fi fi
} }
function ModifyHostFile(){ function ModifyHostFile(){
if $addmode; then if $addmode; then
#add domains to the hosts file #add domains to the hosts file
if [[ -r $blacklist ]];then if [[ -r $blacklist ]];then
numberOf=$(cat $blacklist | sed '/^\s*$/d' | wc -l) numberOf=$(cat $blacklist | sed '/^\s*$/d' | wc -l)
plural=; [[ "$numberOf" != "1" ]] && plural=s plural=; [[ "$numberOf" != "1" ]] && plural=s
echo ":::" echo ":::"
echo -n "::: Modifying HOSTS file to blacklist $numberOf domain${plural}..." echo -n "::: Modifying HOSTS file to blacklist $numberOf domain${plural}..."
if [[ -n $piholeIPv6 ]];then if [[ -n $piholeIPv6 ]];then
cat $blacklist | awk -v ipv4addr="$piholeIP" -v ipv6addr="$piholeIPv6" '{sub(/\r$/,""); print ipv4addr" "$0"\n"ipv6addr" "$0}' >> $adList cat $blacklist | awk -v ipv4addr="$piholeIP" -v ipv6addr="$piholeIPv6" '{sub(/\r$/,""); print ipv4addr" "$0"\n"ipv6addr" "$0}' >> $adList
else else
cat $blacklist | awk -v ipv4addr="$piholeIP" '{sub(/\r$/,""); print ipv4addr" "$0}' >>$adList cat $blacklist | awk -v ipv4addr="$piholeIP" '{sub(/\r$/,""); print ipv4addr" "$0}' >>$adList
fi fi
fi fi
else else
echo ":::" echo ":::"
for dom in "${domToRemoveList[@]}" for dom in "${domToRemoveList[@]}"
do do
#we need to remove the domains from the blacklist file and the host file #we need to remove the domains from the blacklist file and the host file
echo "::: $dom" echo "::: $dom"
echo -n "::: removing from HOSTS file..." echo -n "::: removing from HOSTS file..."
echo $dom | sed 's/\./\\./g' | xargs -I {} perl -i -ne'print unless /[^.]'{}'(?!.)/;' $adList echo "$dom" | sed 's/\./\\./g' | xargs -I {} perl -i -ne'print unless /[^.]'{}'(?!.)/;' $adList
echo " done!" echo " done!"
echo -n "::: removing from blackist.txt..." echo -n "::: removing from blackist.txt..."
echo $dom | sed 's/\./\\./g' | xargs -I {} perl -i -ne'print unless /'{}'(?!.)/;' $blacklist echo "$dom" | sed 's/\./\\./g' | xargs -I {} perl -i -ne'print unless /'{}'(?!.)/;' $blacklist
echo " done!" echo " done!"
done done
fi fi
} }
function Reload() { function Reload() {
@ -157,34 +187,47 @@ function Reload() {
if [[ $dnsmasqPid ]]; then if [[ $dnsmasqPid ]]; then
# service already running - reload config # service already running - reload config
sudo kill -HUP $dnsmasqPid $SUDO killall -s HUP dnsmasq
else else
# service not running, start it up # service not running, start it up
sudo service dnsmasq start $SUDO service dnsmasq start
fi fi
echo " done!" echo " done!"
} }
function DisplayBlist() {
verbose=false
echo -e " Displaying Gravity Affected Domains \n"
count=1
while IFS= read -r AD
do
echo "${count}: $AD"
count=$((count+1))
done < "$blacklist"
}
################################################### ###################################################
for var in "$@" for var in "$@"
do do
case "$var" in case "$var" in
"-nr"| "--noreload" ) reload=false;; "-nr"| "--noreload" ) reload=false;;
"-d" | "--delmode" ) addmode=false;; "-d" | "--delmode" ) addmode=false;;
"-f" | "--force" ) force=true;; "-f" | "--force" ) force=true;;
"-q" | "--quiet" ) versbose=false;; "-q" | "--quiet" ) verbose=false;;
* ) HandleOther $var;; "-h" | "--help" ) helpFunc;;
"-l" | "--list" ) DisplayBlist;;
* ) HandleOther "$var";;
esac esac
done done
PopBlacklistFile PopBlacklistFile
if $modifyHost || $force; then if $modifyHost || $force; then
ModifyHostFile ModifyHostFile
else else
if $versbose; then if $verbose; then
echo "::: No changes need to be made" echo "::: No changes need to be made"
fi fi
exit 1 exit 1
fi fi

View file

@ -51,9 +51,13 @@ function CalcblockedToday(){
function CalcPercentBlockedToday(){ function CalcPercentBlockedToday(){
if [ "$queriesToday" != "Err." ] && [ "$blockedToday" != "Err." ]; then if [ "$queriesToday" != "Err." ] && [ "$blockedToday" != "Err." ]; then
#scale 2 rounds the number down, so we'll do scale 4 and then trim the last 2 zeros if [ "$queriesToday" != 0 ]; then #Fixes divide by zero error :)
percentBlockedToday=$(echo "scale=4; $blockedToday/$queriesToday*100" | bc) #scale 2 rounds the number down, so we'll do scale 4 and then trim the last 2 zeros
percentBlockedToday=$(sed 's/.\{2\}$//' <<< "$percentBlockedToday") percentBlockedToday=$(echo "scale=4; $blockedToday/$queriesToday*100" | bc)
percentBlockedToday=$(sed 's/.\{2\}$//' <<< "$percentBlockedToday")
else
percentBlockedToday=0
fi
fi fi
} }
@ -69,9 +73,9 @@ function outputJSON(){
CalcQueriesToday CalcQueriesToday
CalcblockedToday CalcblockedToday
CalcPercentBlockedToday CalcPercentBlockedToday
CalcBlockedDomains CalcBlockedDomains
printf '{"domains_being_blocked":"%s","dns_queries_today":"%s","ads_blocked_today":"%s","ads_percentage_today":"%s"}\n' "$blockedDomainsTotal" "$queriesToday" "$blockedToday" "$percentBlockedToday" printf '{"domains_being_blocked":"%s","dns_queries_today":"%s","ads_blocked_today":"%s","ads_percentage_today":"%s"}\n' "$blockedDomainsTotal" "$queriesToday" "$blockedToday" "$percentBlockedToday"
} }
@ -80,47 +84,53 @@ function normalChrono(){
do do
clear clear
# Displays a colorful Pi-hole logo # Displays a colorful Pi-hole logo
toilet -f small -F gay Pi-hole echo " ___ _ _ _"
echo "| _ (_)___| |_ ___| |___"
echo "| _/ |___| ' \/ _ \ / -_)"
echo "|_| |_| |_||_\___/_\___|"
echo ""
echo " $(ifconfig eth0 | awk '/inet addr/ {print $2}' | cut -d':' -f2)" echo " $(ifconfig eth0 | awk '/inet addr/ {print $2}' | cut -d':' -f2)"
echo "" echo ""
uptime | cut -d' ' -f11- uptime | cut -d' ' -f11-
#uptime -p #Doesn't work on all versions of uptime
uptime | awk -F'( |,|:)+' '{if ($7=="min") m=$6; else {if ($7~/^day/) {d=$6;h=$8;m=$9} else {h=$6;m=$7}}} {print d+0,"days,",h+0,"hours,",m+0,"minutes."}'
echo "-------------------------------" echo "-------------------------------"
# Uncomment to continually read the log file and display the current domain being blocked # Uncomment to continually read the log file and display the current domain being blocked
#tail -f /var/log/pihole.log | awk '/\/etc\/pihole\/gravity.list/ {if ($7 != "address" && $7 != "name" && $7 != "/etc/pihole/gravity.list") print $7; else;}' #tail -f /var/log/pihole.log | awk '/\/etc\/pihole\/gravity.list/ {if ($7 != "address" && $7 != "name" && $7 != "/etc/pihole/gravity.list") print $7; else;}'
#uncomment next 4 lines to use original query count calculation #uncomment next 4 lines to use original query count calculation
#today=$(date "+%b %e") #today=$(date "+%b %e")
#todaysQueryCount=$(cat /var/log/pihole.log | grep "$today" | awk '/query/ {print $7}' | wc -l) #todaysQueryCount=$(cat /var/log/pihole.log | grep "$today" | awk '/query/ {print $7}' | wc -l)
#todaysQueryCountV4=$(cat /var/log/pihole.log | grep "$today" | awk '/query/ && /\[A\]/ {print $7}' | wc -l) #todaysQueryCountV4=$(cat /var/log/pihole.log | grep "$today" | awk '/query/ && /\[A\]/ {print $7}' | wc -l)
#todaysQueryCountV6=$(cat /var/log/pihole.log | grep "$today" | awk '/query/ && /\[AAAA\]/ {print $7}' | wc -l) #todaysQueryCountV6=$(cat /var/log/pihole.log | grep "$today" | awk '/query/ && /\[AAAA\]/ {print $7}' | wc -l)
CalcQueriesToday CalcQueriesToday
CalcblockedToday CalcblockedToday
CalcPercentBlockedToday CalcPercentBlockedToday
CalcBlockedDomains CalcBlockedDomains
echo "Blocking: $blockedDomainsTotal" echo "Blocking: $blockedDomainsTotal"
#below commented line does not add up to todaysQueryCount #below commented line does not add up to todaysQueryCount
#echo "Queries: $todaysQueryCountV4 / $todaysQueryCountV6" #echo "Queries: $todaysQueryCountV4 / $todaysQueryCountV6"
echo "Queries: $queriesToday" #same total calculation as dashboard echo "Queries: $queriesToday" #same total calculation as dashboard
echo "Pi-holed: $blockedToday ($percentBlockedToday%)" echo "Pi-holed: $blockedToday ($percentBlockedToday%)"
sleep 5 sleep 5
done done
} }
function displayHelp(){ function displayHelp(){
echo "Displays stats about your piHole!" echo "::: Displays stats about your piHole!"
echo " " echo ":::"
echo "Usage: chronometer.sh [optional:-j]" echo "::: Usage: sudo pihole -c [optional:-j]"
echo "Note: If no option is passed, then stats are displayed on screen, updated every 5 seconds" echo "::: Note: If no option is passed, then stats are displayed on screen, updated every 5 seconds"
echo " " echo ":::"
echo "Options:" echo "::: Options:"
echo " -j, --json output stats as JSON formatted string" echo "::: -j, --json output stats as JSON formatted string"
echo " -h, --help display this help text" echo "::: -h, --help display this help text"
exit 1 exit 1
} }
@ -132,7 +142,7 @@ for var in "$@"
do do
case "$var" in case "$var" in
"-j" | "--json" ) outputJSON;; "-j" | "--json" ) outputJSON;;
"-h" | "--help" ) displayHelp;; "-h" | "--help" ) displayHelp;;
* ) exit 1;; * ) exit 1;;
esac esac
done done

364
advanced/Scripts/piholeDebug.sh Executable file
View file

@ -0,0 +1,364 @@
#!/usr/bin/env bash
# Pi-hole: A black hole for Internet advertisements
# (c) 2015, 2016 by Jacob Salmela
# Network-wide ad blocking via your Raspberry Pi
# http://pi-hole.net
# Generates pihole_debug.log in /var/log/ to be used for troubleshooting.
#
# Pi-hole is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
######## GLOBAL VARS ########
DEBUG_LOG="/var/log/pihole_debug.log"
DNSMASQFILE="/etc/dnsmasq.conf"
PIHOLECONFFILE="/etc/dnsmasq.d/01-pihole.conf"
LIGHTTPDFILE="/etc/lighttpd/lighttpd.conf"
LIGHTTPDERRFILE="/var/log/lighttpd/error.log"
GRAVITYFILE="/etc/pihole/gravity.list"
HOSTSFILE="/etc/hosts"
WHITELISTFILE="/etc/pihole/whitelist.txt"
BLACKLISTFILE="/etc/pihole/blacklist.txt"
ADLISTSFILE="/etc/pihole/adlists.list"
PIHOLELOG="/var/log/pihole.log"
WHITELISTMATCHES="/tmp/whitelistmatches.list"
######## FIRST CHECK ########
# Must be root to debug
if [[ $EUID -eq 0 ]]; then
echo "::: You are root... Beginning debug!"
else
echo "::: Sudo will be used for debugging."
# Check if sudo is actually installed
if [ -x "$(command -v sudo)" ]; then
export SUDO="sudo"
else
echo "::: Please install sudo or run this as root."
exit 1
fi
fi
# Ensure the file exists, create if not, clear if exists.
if [ ! -f "$DEBUG_LOG" ]; then
$SUDO touch $DEBUG_LOG
$SUDO chmod 644 $DEBUG_LOG
$SUDO chown "$USER":root $DEBUG_LOG
else
truncate -s 0 $DEBUG_LOG
fi
### Private functions exist here ###
function versionCheck {
echo "#######################################" >> $DEBUG_LOG
echo "########## Versions Section ###########" >> $DEBUG_LOG
echo "#######################################" >> $DEBUG_LOG
TMP=$(cd /etc/.pihole/ && git describe --tags --abbrev=0)
echo "Pi-hole Version: $TMP" >> $DEBUG_LOG
TMP=$(cd /var/www/html/admin && git describe --tags --abbrev=0)
echo "WebUI Version: $TMP" >> $DEBUG_LOG
echo >> $DEBUG_LOG
}
function distroCheck {
echo "#######################################" >> $DEBUG_LOG
echo "######## Distribution Section #########" >> $DEBUG_LOG
echo "#######################################" >> $DEBUG_LOG
TMP=$(cat /etc/*release || echo "Failed to find release")
echo "Distribution Version: $TMP" >> $DEBUG_LOG
}
function compareWhitelist {
if [ ! -f "$WHITELISTMATCHES" ]; then
$SUDO touch $WHITELISTMATCHES
$SUDO chmod 644 $WHITELISTMATCHES
$SUDO chown "$USER":root $WHITELISTMATCHES
else
truncate -s 0 $WHITELISTMATCHES
fi
echo "#######################################" >> $DEBUG_LOG
echo "######## Whitelist Comparison #########" >> $DEBUG_LOG
echo "#######################################" >> $DEBUG_LOG
while read -r line; do
TMP=$(grep -w ".* $line$" "$GRAVITYFILE")
if [ ! -z "$TMP" ]; then
echo "$TMP" >> $DEBUG_LOG
echo "$TMP" >> $WHITELISTMATCHES
fi
done < "$WHITELISTFILE"
echo >> $DEBUG_LOG
}
function compareBlacklist {
echo "#######################################" >> $DEBUG_LOG
echo "######## Blacklist Comparison #########" >> $DEBUG_LOG
echo "#######################################" >> $DEBUG_LOG
while read -r line; do
if [ ! -z "$line" ]; then
grep -w ".* $line$" "$GRAVITYFILE" >> $DEBUG_LOG
fi
done < "$BLACKLISTFILE"
echo >> $DEBUG_LOG
}
function testNslookup {
TESTURL="doubleclick.com"
echo "#######################################" >> $DEBUG_LOG
echo "############ NSLookup Test ############" >> $DEBUG_LOG
echo "#######################################" >> $DEBUG_LOG
# Find a blocked url that has not been whitelisted.
if [ -s "$WHITELISTMATCHES" ]; then
while read -r line; do
CUTURL=${line#*" "}
if [ "$CUTURL" != "Pi-Hole.IsWorking.OK" ]; then
while read -r line2; do
CUTURL2=${line2#*" "}
if [ "$CUTURL" != "$CUTURL2" ]; then
TESTURL="$CUTURL"
break 2
fi
done < "$WHITELISTMATCHES"
fi
done < "$GRAVITYFILE"
fi
echo "NSLOOKUP of $TESTURL from PiHole:" >> $DEBUG_LOG
nslookup "$TESTURL" >> $DEBUG_LOG
echo >> $DEBUG_LOG
echo "NSLOOKUP of $TESTURL from 8.8.8.8:" >> $DEBUG_LOG
nslookup "$TESTURL" 8.8.8.8 >> $DEBUG_LOG
echo >> $DEBUG_LOG
}
function checkProcesses {
echo "#######################################" >> $DEBUG_LOG
echo "########### Processes Check ###########" >> $DEBUG_LOG
echo "#######################################" >> $DEBUG_LOG
echo ":::"
echo "::: Logging status of lighttpd and dnsmasq..."
PROCESSES=( lighttpd dnsmasq )
for i in "${PROCESSES[@]}"
do
echo "" >> $DEBUG_LOG
echo -n "$i" >> "$DEBUG_LOG"
echo " processes status:" >> $DEBUG_LOG
$SUDO systemctl -l status "$i" >> "$DEBUG_LOG"
done
}
function debugLighttpd {
echo "::: Writing lighttpd to debug log..."
echo "#######################################" >> $DEBUG_LOG
echo "############ lighttpd.conf ############" >> $DEBUG_LOG
echo "#######################################" >> $DEBUG_LOG
if [ -e "$LIGHTTPDFILE" ]
then
while read -r line; do
if [ ! -z "$line" ]; then
[[ "$line" =~ ^#.*$ ]] && continue
echo "$line" >> $DEBUG_LOG
fi
done < "$LIGHTTPDFILE"
echo >> $DEBUG_LOG
else
echo "No lighttpd.conf file found!" >> $DEBUG_LOG
printf ":::\tNo lighttpd.conf file found\n"
fi
if [ -e "$LIGHTTPDERRFILE" ]
then
echo "#######################################" >> $DEBUG_LOG
echo "######### lighttpd error.log ##########" >> $DEBUG_LOG
echo "#######################################" >> $DEBUG_LOG
cat "$LIGHTTPDERRFILE" >> $DEBUG_LOG
else
echo "No lighttpd error.log file found!" >> $DEBUG_LOG
printf ":::\tNo lighttpd error.log file found\n"
fi
echo >> $DEBUG_LOG
}
### END FUNCTIONS ###
### Check Pi internet connections ###
# Log the IP addresses of this Pi
IPADDR=$($SUDO ifconfig | perl -nle 's/dr:(\S+)/print $1/e')
echo "::: Writing local IPs to debug log"
echo "IP Addresses of this Pi:" >> $DEBUG_LOG
echo "$IPADDR" >> $DEBUG_LOG
echo >> $DEBUG_LOG
# Check if we can connect to the local gateway
GATEWAY_CHECK=$(ping -q -w 1 -c 1 "$(ip r | grep default | cut -d ' ' -f 3)" > /dev/null && echo ok || echo error)
echo "Gateway check:" >> $DEBUG_LOG
echo "$GATEWAY_CHECK" >> $DEBUG_LOG
echo >> $DEBUG_LOG
versionCheck
distroCheck
compareWhitelist
compareBlacklist
testNslookup
checkProcesses
debugLighttpd
echo "::: Writing dnsmasq.conf to debug log..."
echo "#######################################" >> $DEBUG_LOG
echo "############### Dnsmasq ###############" >> $DEBUG_LOG
echo "#######################################" >> $DEBUG_LOG
if [ -e "$DNSMASQFILE" ]
then
#cat $DNSMASQFILE >> $DEBUG_LOG
while read -r line; do
if [ ! -z "$line" ]; then
[[ "$line" =~ ^#.*$ ]] && continue
echo "$line" >> $DEBUG_LOG
fi
done < "$DNSMASQFILE"
echo >> $DEBUG_LOG
else
echo "No dnsmasq.conf file found!" >> $DEBUG_LOG
printf ":::\tNo dnsmasq.conf file found!\n"
fi
echo "::: Writing 01-pihole.conf to debug log..."
echo "#######################################" >> $DEBUG_LOG
echo "########### 01-pihole.conf ############" >> $DEBUG_LOG
echo "#######################################" >> $DEBUG_LOG
if [ -e "$PIHOLECONFFILE" ]
then
while read -r line; do
if [ ! -z "$line" ]; then
[[ "$line" =~ ^#.*$ ]] && continue
echo "$line" >> $DEBUG_LOG
fi
done < "$PIHOLECONFFILE"
echo >> $DEBUG_LOG
else
echo "No 01-pihole.conf file found!" >> $DEBUG_LOG
printf ":::\tNo 01-pihole.conf file found\n"
fi
echo "::: Writing size of gravity.list to debug log..."
echo "#######################################" >> $DEBUG_LOG
echo "############ gravity.list #############" >> $DEBUG_LOG
echo "#######################################" >> $DEBUG_LOG
if [ -e "$GRAVITYFILE" ]
then
wc -l "$GRAVITYFILE" >> $DEBUG_LOG
echo >> $DEBUG_LOG
else
echo "No gravity.list file found!" >> $DEBUG_LOG
printf ":::\tNo gravity.list file found\n"
fi
# Write the hostname output to compare against entries in /etc/hosts, which is logged next
echo "Hostname of this pihole is: " >> $DEBUG_LOG
hostname >> $DEBUG_LOG
echo "::: Writing hosts file to debug log..."
echo "#######################################" >> $DEBUG_LOG
echo "################ Hosts ################" >> $DEBUG_LOG
echo "#######################################" >> $DEBUG_LOG
if [ -e "$HOSTSFILE" ]
then
cat "$HOSTSFILE" >> $DEBUG_LOG
echo >> $DEBUG_LOG
else
echo "No hosts file found!" >> $DEBUG_LOG
printf ":::\tNo hosts file found!\n"
fi
### PiHole application specific logging ###
echo "::: Writing whitelist to debug log..."
echo "#######################################" >> $DEBUG_LOG
echo "############## Whitelist ##############" >> $DEBUG_LOG
echo "#######################################" >> $DEBUG_LOG
if [ -e "$WHITELISTFILE" ]
then
cat "$WHITELISTFILE" >> $DEBUG_LOG
echo >> $DEBUG_LOG
else
echo "No whitelist.txt file found!" >> $DEBUG_LOG
printf ":::\tNo whitelist.txt file found!\n"
fi
echo "::: Writing blacklist to debug log..."
echo "#######################################" >> $DEBUG_LOG
echo "############## Blacklist ##############" >> $DEBUG_LOG
echo "#######################################" >> $DEBUG_LOG
if [ -e "$BLACKLISTFILE" ]
then
cat "$BLACKLISTFILE" >> $DEBUG_LOG
echo >> $DEBUG_LOG
else
echo "No blacklist.txt file found!" >> $DEBUG_LOG
printf ":::\tNo blacklist.txt file found!\n"
fi
echo "::: Writing adlists.list to debug log..."
echo "#######################################" >> $DEBUG_LOG
echo "############ adlists.list #############" >> $DEBUG_LOG
echo "#######################################" >> $DEBUG_LOG
if [ -e "$ADLISTSFILE" ]
then
cat "$ADLISTSFILE" >> $DEBUG_LOG
echo >> $DEBUG_LOG
else
echo "No adlists.list file found... using adlists.default!" >> $DEBUG_LOG
printf ":::\tNo adlists.list file found... using adlists.default!\n"
fi
# Continuously append the pihole.log file to the pihole_debug.log file
function dumpPiHoleLog {
trap '{ echo -e "\n::: Finishing debug write from interrupt... Quitting!" ; exit 1; }' INT
echo -e "::: Writing current pihole traffic to debug log...\n:::\tTry loading any/all sites that you are having trouble with now... \n:::\t(Press ctrl+C to finish)"
echo "#######################################" >> $DEBUG_LOG
echo "############# pihole.log ##############" >> $DEBUG_LOG
echo "#######################################" >> $DEBUG_LOG
if [ -e "$PIHOLELOG" ]
then
while true; do
tail -f "$PIHOLELOG" >> $DEBUG_LOG
echo >> $DEBUG_LOG
done
else
echo "No pihole.log file found!" >> $DEBUG_LOG
printf ":::\tNo pihole.log file found!\n"
fi
}
# Anything to be done after capturing of pihole.log terminates
function finalWork {
echo "::: Finshed debugging!"
echo "::: The degug log can be uploaded to Termbin.com for easier sharing."
read -r -p "::: Would you like to upload the log? [y/N] " response
case $response in
[yY][eE][sS]|[yY])
TERMBIN=$(cat /var/log/pihole_debug.log | nc termbin.com 9999)
;;
*)
echo "::: Log will NOT be uploaded to Termbin."
;;
esac
# Check if termbin.com is reachable. When it's not, point to local log instead
if [ -n "$TERMBIN" ]
then
echo "::: Debug log can be found at : $TERMBIN"
else
echo "::: Debug log can be found at : /var/log/pihole_debug.log"
fi
}
trap finalWork EXIT
### Method calls for additional logging ###
dumpPiHoleLog

View file

@ -10,4 +10,6 @@
# the Free Software Foundation, either version 2 of the License, or # the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version. # (at your option) any later version.
echo -n "::: Flushing /var/log/pihole.log ..."
truncate -s 0 /var/log/pihole.log truncate -s 0 /var/log/pihole.log
echo "... done!"

89
advanced/Scripts/setupLCD.sh Executable file
View file

@ -0,0 +1,89 @@
#!/usr/bin/env bash
# Pi-hole: A black hole for Internet advertisements
# (c) 2015 by Jacob Salmela
# Network-wide ad blocking via your Raspberry Pi
# http://pi-hole.net
# Automatically configures the Pi to use the 2.8 LCD screen to display stats on it (also works over ssh)
#
# Pi-hole is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
############ FUNCTIONS ###########
# Run this script as root or under sudo
echo ":::"
if [[ $EUID -eq 0 ]];then
echo "::: You are root."
else
echo "::: sudo will be used."
# Check if it is actually installed
# If it isn't, exit because the install cannot complete
if [ -x "$(command -v sudo)" ];then
export SUDO="sudo"
else
echo "::: Please install sudo or run this script as root."
exit 1
fi
fi
# Borrowed from adafruit-pitft-helper < borrowed from raspi-config
# https://github.com/adafruit/Adafruit-PiTFT-Helper/blob/master/adafruit-pitft-helper#L324-L334
getInitSys() {
if command -v systemctl > /dev/null && systemctl | grep -q '\-\.mount'; then
SYSTEMD=1
elif [ -f /etc/init.d/cron ] && [ ! -h /etc/init.d/cron ]; then
SYSTEMD=0
else
echo "Unrecognised init system"
return 1
fi
}
# Borrowed from adafruit-pitft-helper:
# https://github.com/adafruit/Adafruit-PiTFT-Helper/blob/master/adafruit-pitft-helper#L274-L285
autoLoginPiToConsole() {
if [ -e /etc/init.d/lightdm ]; then
if [ $SYSTEMD -eq 1 ]; then
$SUDO systemctl set-default multi-user.target
$SUDO ln -fs /etc/systemd/system/autologin@.service /etc/systemd/system/getty.target.wants/getty@tty1.service
else
$SUDO update-rc.d lightdm disable 2
$SUDO sed /etc/inittab -i -e "s/1:2345:respawn:\/sbin\/getty --noclear 38400 tty1/1:2345:respawn:\/bin\/login -f pi tty1 <\/dev\/tty1 >\/dev\/tty1 2>&1/"
fi
fi
}
######### SCRIPT ###########
# Set pi to log in automatically
getInitSys
autoLoginPiToConsole
# Set chronomter to run automatically when pi logs in
echo /usr/local/bin/chronometer.sh >> /home/pi/.bashrc
# OR
#$SUDO echo /usr/local/bin/chronometer.sh >> /etc/profile
# Set up the LCD screen based on Adafruits instuctions:
# https://learn.adafruit.com/adafruit-pitft-28-inch-resistive-touchscreen-display-raspberry-pi/easy-install
curl -SLs https://apt.adafruit.com/add-pin | $SUDO bash
$SUDO apt-get -y install raspberrypi-bootloader
$SUDO apt-get -y install adafruit-pitft-helper
$SUDO adafruit-pitft-helper -t 28r
# Download the cmdline.txt file that prevents the screen from going blank after a period of time
$SUDO mv /boot/cmdline.txt /boot/cmdline.orig
$SUDO curl -o /boot/cmdline.txt https://raw.githubusercontent.com/pi-hole/pi-hole/master/advanced/cmdline.txt
# Back up the original file and download the new one
$SUDO mv /etc/default/console-setup /etc/default/console-setup.orig
$SUDO curl -o /etc/default/console-setup https://raw.githubusercontent.com/pi-hole/pi-hole/master/advanced/console-setup
# Instantly apply the font change to the LCD screen
$SUDO setupcon
$SUDO reboot
# Start showing the stats on the screen by running the command on another tty:
# http://unix.stackexchange.com/questions/170063/start-a-process-on-a-different-tty
#setsid sh -c 'exec /usr/local/bin/chronometer.sh <> /dev/tty1 >&0 2>&1'

2
advanced/Scripts/updateDashboard.sh Normal file → Executable file
View file

@ -63,7 +63,7 @@ make_repo() {
update_repo() { update_repo() {
# pull the latest commits # pull the latest commits
cd "$WEB_INTERFACE_DIR" cd "$WEB_INTERFACE_DIR"
git pull git pull
} }
main main

View file

@ -0,0 +1,20 @@
#!/usr/bin/env bash
# Pi-hole: A black hole for Internet advertisements
# (c) 2015, 2016 by Jacob Salmela
# Network-wide ad blocking via your Raspberry Pi
# http://pi-hole.net
# Whitelists domains
#
# Pi-hole is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
piholeVersion=$(cd /etc/.pihole/ && git describe --tags --abbrev=0)
webVersion=$(cd /var/www/html/admin/ && git describe --tags --abbrev=0)
piholeVersionLatest=$(curl -s https://api.github.com/repos/pi-hole/pi-hole/releases/latest | grep -Po '"tag_name":.*?[^\\]",' | perl -pe 's/"tag_name": "//; s/^"//; s/",$//')
webVersionLatest=$(curl -s https://api.github.com/repos/pi-hole/AdminLTE/releases/latest | grep -Po '"tag_name":.*?[^\\]",' | perl -pe 's/"tag_name": "//; s/^"//; s/",$//')
echo "::: Pi-hole version is $piholeVersion (Latest version is $piholeVersionLatest)"
echo "::: Web-Admin version is $webVersion (Latest version is $webVersionLatest)"

View file

@ -10,53 +10,87 @@
# the Free Software Foundation, either version 2 of the License, or # the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version. # (at your option) any later version.
#rootcheck
if [[ $EUID -eq 0 ]];then
echo "::: You are root."
else
echo "::: sudo will be used."
# Check if it is actually installed
# If it isn't, exit because the install cannot complete
if [ -x "$(command -v sudo)" ];then
export SUDO="sudo"
else
echo "::: Please install sudo or run this script as root."
exit 1
fi
fi
function helpFunc()
{
echo "::: Immediately whitelists one or more domains in the hosts file"
echo ":::"
echo "::: Usage: pihole -w domain1 [domain2 ...]"
echo ":::"
echo "::: Options:"
echo "::: -d, --delmode Remove domains from the whitelist"
echo "::: -nr, --noreload Update Whitelist without refreshing dnsmasq"
echo "::: -f, --force Force updating of the hosts files, even if there are no changes"
echo "::: -q, --quiet output is less verbose"
echo "::: -h, --help Show this help dialog"
echo "::: -l, --list Display your whitelisted domains"
exit 1
}
if [[ $# = 0 ]]; then if [[ $# = 0 ]]; then
echo "Immediately whitelists one or more domains in the hosts file" helpFunc
echo " "
echo "Usage: whitelist.sh domain1 [domain2 ...]"
echo " "
echo "Options:"
echo " -d, --delmode Remove domains from the whitelist"
echo " -nr, --noreload Update Whitelist without refreshing dnsmasq"
echo " -f, --force Force updating of the hosts files, even if there are no changes"
echo " -q, --quiet output is less verbose"
exit 1
fi fi
#globals #globals
whitelist=/etc/pihole/whitelist.txt basename=pihole
adList=/etc/pihole/gravity.list piholeDir=/etc/$basename
adList=$piholeDir/gravity.list
whitelist=$piholeDir/whitelist.txt
reload=true reload=true
addmode=true addmode=true
force=false force=false
versbose=true verbose=true
domList=() domList=()
domToRemoveList=() domToRemoveList=()
piholeIPfile=/tmp/piholeIP piholeIPfile=/etc/pihole/piholeIP
piholeIPv6file=/etc/pihole/.useIPv6 piholeIPv6file=/etc/pihole/.useIPv6
# Otherwise, the IP address can be taken directly from the machine, which will happen when the script is run by the user and not the installation script if [[ -f $piholeIPfile ]];then
IPv4dev=$(ip route get 8.8.8.8 | awk '{for(i=1;i<=NF;i++)if($i~/dev/)print $(i+1)}') # If the file exists, it means it was exported from the installation script and we should use that value instead of detecting it in this script
piholeIPCIDR=$(ip -o -f inet addr show dev $IPv4dev | awk '{print $4}' | awk 'END {print}') piholeIP=$(cat $piholeIPfile)
piholeIP=${piholeIPCIDR%/*} #rm $piholeIPfile
else
# Otherwise, the IP address can be taken directly from the machine, which will happen when the script is run by the user and not the installation script
IPv4dev=$(ip route get 8.8.8.8 | awk '{for(i=1;i<=NF;i++)if($i~/dev/)print $(i+1)}')
piholeIPCIDR=$(ip -o -f inet addr show dev "$IPv4dev" | awk '{print $4}' | awk 'END {print}')
piholeIP=${piholeIPCIDR%/*}
fi
modifyHost=false modifyHost=false
# After setting defaults, check if there's local overrides
if [[ -r $piholeDir/pihole.conf ]];then
echo "::: Local calibration requested..."
. $piholeDir/pihole.conf
fi
if [[ -f $piholeIPv6file ]];then if [[ -f $piholeIPv6file ]];then
# If the file exists, then the user previously chose to use IPv6 in the automated installer # If the file exists, then the user previously chose to use IPv6 in the automated installer
piholeIPv6=$(ip -6 route get 2001:4860:4860::8888 | awk -F " " '{ for(i=1;i<=NF;i++) if ($i == "src") print $(i+1) }') piholeIPv6=$(ip -6 route get 2001:4860:4860::8888 | awk -F " " '{ for(i=1;i<=NF;i++) if ($i == "src") print $(i+1) }')
fi fi
function HandleOther(){
function HandleOther(){
#check validity of domain #check validity of domain
validDomain=$(echo $1 | perl -ne'print if /\b((?=[a-z0-9-]{1,63}\.)(xn--)?[a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,63}\b/') validDomain=$(echo "$1" | perl -ne'print if /\b((?=[a-z0-9-]{1,63}\.)(xn--)?[a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,63}\b/')
if [ -z "$validDomain" ]; then if [ -z "$validDomain" ]; then
echo "::: $1 is not a valid argument or domain name" echo "::: $1 is not a valid argument or domain name"
else else
domList=("${domList[@]}" $validDomain) domList=("${domList[@]}" $validDomain)
fi fi
} }
@ -65,13 +99,13 @@ function PopWhitelistFile(){
#check whitelist file exists, and if not, create it #check whitelist file exists, and if not, create it
if [[ ! -f $whitelist ]];then if [[ ! -f $whitelist ]];then
touch $whitelist touch $whitelist
fi fi
for dom in "${domList[@]}" for dom in "${domList[@]}"
do do
if $addmode; then if $addmode; then
AddDomain $dom AddDomain "$dom"
else else
RemoveDomain $dom RemoveDomain "$dom"
fi fi
done done
} }
@ -79,45 +113,45 @@ function PopWhitelistFile(){
function AddDomain(){ function AddDomain(){
#| sed 's/\./\\./g' #| sed 's/\./\\./g'
bool=false bool=false
grep -Ex -q "$1" $whitelist || bool=true grep -Ex -q "$1" $whitelist || bool=true
if $bool; then if $bool; then
#domain not found in the whitelist file, add it! #domain not found in the whitelist file, add it!
if $versbose; then if $verbose; then
echo -n "::: Adding $1 to whitelist.txt..." echo -n "::: Adding $1 to $whitelist..."
fi fi
echo $1 >> $whitelist echo "$1" >> $whitelist
modifyHost=true modifyHost=true
if $versbose; then if $verbose; then
echo " done!" echo " done!"
fi fi
else else
if $versbose; then if $verbose; then
echo "::: $1 already exists in whitelist.txt, no need to add!" echo "::: $1 already exists in $whitelist, no need to add!"
fi fi
fi fi
} }
function RemoveDomain(){ function RemoveDomain(){
bool=false bool=false
grep -Ex -q "$1" $whitelist || bool=true grep -Ex -q "$1" $whitelist || bool=true
if $bool; then if $bool; then
#Domain is not in the whitelist file, no need to Remove #Domain is not in the whitelist file, no need to Remove
if $versbose; then if $verbose; then
echo "::: $1 is NOT whitelisted! No need to remove" echo "::: $1 is NOT whitelisted! No need to remove"
fi fi
else else
#Domain is in the whitelist file, add to a temporary array and remove from whitelist file #Domain is in the whitelist file, add to a temporary array and remove from whitelist file
#if $versbose; then #if $verbose; then
#echo "::: Un-whitelisting $dom..." #echo "::: Un-whitelisting $dom..."
#fi #fi
domToRemoveList=("${domToRemoveList[@]}" $1) domToRemoveList=("${domToRemoveList[@]}" $1)
modifyHost=true modifyHost=true
fi fi
} }
function ModifyHostFile(){ function ModifyHostFile(){
if $addmode; then if $addmode; then
#remove domains in from hosts file #remove domains in from hosts file
if [[ -r $whitelist ]];then if [[ -r $whitelist ]];then
@ -126,36 +160,39 @@ function ModifyHostFile(){
plural=; [[ "$numberOf" != "1" ]] && plural=s plural=; [[ "$numberOf" != "1" ]] && plural=s
echo ":::" echo ":::"
echo -n "::: Modifying HOSTS file to whitelist $numberOf domain${plural}..." echo -n "::: Modifying HOSTS file to whitelist $numberOf domain${plural}..."
awk -F':' '{print $1}' $whitelist | while read line; do echo "$piholeIP $line"; done > /etc/pihole/whitelist.tmp awk -F':' '{print $1}' $whitelist | while read -r line; do echo "$piholeIP $line"; done > /etc/pihole/whitelist.tmp
awk -F':' '{print $1}' $whitelist | while read line; do echo "$piholeIPv6 $line"; done >> /etc/pihole/whitelist.tmp awk -F':' '{print $1}' $whitelist | while read -r line; do echo "$piholeIPv6 $line"; done >> /etc/pihole/whitelist.tmp
echo "l" >> /etc/pihole/whitelist.tmp echo "l" >> /etc/pihole/whitelist.tmp
grep -F -x -v -f /etc/pihole/whitelist.tmp /etc/pihole/gravity.list > /etc/pihole/gravity.tmp grep -F -x -v -f $piholeDir/whitelist.tmp $adList > $piholeDir/gravity.tmp
rm /etc/pihole/gravity.list rm $adList
mv /etc/pihole/gravity.tmp /etc/pihole/gravity.list mv $piholeDir/gravity.tmp $adList
rm /etc/pihole/whitelist.tmp rm $piholeDir/whitelist.tmp
echo " done!" echo " done!"
fi fi
else else
#we need to add the removed domains to the hosts file #we need to add the removed domains to the hosts file
echo ":::" echo ":::"
echo "::: Modifying HOSTS file to un-whitelist domains..." echo "::: Modifying HOSTS file to un-whitelist domains..."
for rdom in "${domToRemoveList[@]}" for rdom in "${domToRemoveList[@]}"
do do
if [[ -n $piholeIPv6 ]];then if grep -q "$rdom" /etc/pihole/*.domains; then
echo -n "::: Un-whitelisting $rdom on IPv4 and IPv6..." echo "::: AdLists contain $rdom, re-adding block"
echo $rdom | awk -v ipv4addr="$piholeIP" -v ipv6addr="$piholeIPv6" '{sub(/\r$/,""); print ipv4addr" "$0"\n"ipv6addr" "$0}' >> $adList if [[ -n $piholeIPv6 ]];then
echo " done!" echo -n "::: Restoring block for $rdom on IPv4 and IPv6..."
else echo "$rdom" | awk -v ipv4addr="$piholeIP" -v ipv6addr="$piholeIPv6" '{sub(/\r$/,""); print ipv4addr" "$0"\n"ipv6addr" "$0}' >> $adList
echo -n "::: Un-whitelisting $rdom on IPv4" echo " done!"
echo $rdom | awk -v ipv4addr="$piholeIP" '{sub(/\r$/,""); print ipv4addr" "$0}' >>$adList else
echo " done!" echo -n "::: Restoring block for $rdom on IPv4..."
fi echo "$rdom" | awk -v ipv4addr="$piholeIP" '{sub(/\r$/,""); print ipv4addr" "$0}' >>$adList
echo -n "::: Removing $rdom from whitelist.txt..." echo " done!"
echo $rdom| sed 's/\./\\./g' | xargs -I {} perl -i -ne'print unless /'{}'(?!.)/;' $whitelist fi
echo " done!" fi
done echo -n "::: Removing $rdom from $whitelist..."
fi echo "$rdom" | sed 's/\./\\./g' | xargs -I {} perl -i -ne'print unless /'{}'(?!.)/;' $whitelist
echo " done!"
done
fi
} }
function Reload() { function Reload() {
@ -166,24 +203,37 @@ function Reload() {
if [[ $dnsmasqPid ]]; then if [[ $dnsmasqPid ]]; then
# service already running - reload config # service already running - reload config
sudo kill -HUP $dnsmasqPid $SUDO killall -s HUP dnsmasq
else else
# service not running, start it up # service not running, start it up
sudo service dnsmasq start $SUDO service dnsmasq start
fi fi
echo " done!" echo " done!"
} }
function DisplayWlist() {
verbose=false
echo -e " Displaying Gravity Resistant Domains \n"
count=1
while IFS= read -r RD
do
echo "${count}: $RD"
count=$((count+1))
done < "$whitelist"
}
################################################### ###################################################
for var in "$@" for var in "$@"
do do
case "$var" in case "$var" in
"-nr"| "--noreload" ) reload=false;; "-nr"| "--noreload" ) reload=false;;
"-d" | "--delmode" ) addmode=false;; "-d" | "--delmode" ) addmode=false;;
"-f" | "--force" ) force=true;; "-f" | "--force" ) force=true;;
"-q" | "--quiet" ) versbose=false;; "-q" | "--quiet" ) verbose=false;;
* ) HandleOther $var;; "-h" | "--help" ) helpFunc;;
"-l" | "--list" ) DisplayWlist;;
* ) HandleOther "$var";;
esac esac
done done
@ -192,11 +242,11 @@ PopWhitelistFile
if $modifyHost || $force; then if $modifyHost || $force; then
ModifyHostFile ModifyHostFile
else else
if $versbose; then if $verbose; then
echo ":::" echo ":::"
echo "::: No changes need to be made" echo "::: No changes need to be made"
exit 1
fi fi
exit 1
fi fi
if $reload; then if $reload; then

View file

@ -0,0 +1,12 @@
_pihole()
{
local cur prev opts
COMPREPLY=()
cur="${COMP_WORDS[COMP_CWORD]}"
prev="${COMP_WORDS[COMP_CWORD-1]}"
opts="whitelist blacklist debug flush updateDashboard updateGravity setupLCD chronometer uninstall help"
COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
return 0
}
complete -F _pihole pihole

1
advanced/cmdline.txt Normal file
View file

@ -0,0 +1 @@
dwc_otg.lpm_enable=0 console=ttyAMA0,115200 console=tty1 root=/dev/mmcblk0p2 rootfstype=ext4 elevator=deadline fsck.repair=yes rootwait fbcon=map:10 fbcon=font:VGA8x8 consoleblank=0

17
advanced/console-setup Normal file
View file

@ -0,0 +1,17 @@
# CONFIGURATION FILE FOR SETUPCON
# Consult the console-setup(5) manual page.
ACTIVE_CONSOLES="/dev/tty[1-6]"
CHARMAP="UTF-8"
# For best results with the Adafruit 2.8 LCD and Pi-hole's chronometer
CODESET="guess"
FONTFACE="Terminus"
FONTSIZE="10x20"
VIDEOMODE=
# The following is an example how to use a braille font
# FONT='lat9w-08.psf.gz brl-8x8.psf'

View file

@ -27,8 +27,8 @@
# Replies which are not DNSSEC signed may be legitimate, because the domain # Replies which are not DNSSEC signed may be legitimate, because the domain
# is unsigned, or may be forgeries. Setting this option tells dnsmasq to # is unsigned, or may be forgeries. Setting this option tells dnsmasq to
# check that an unsigned reply is OK, by finding a secure proof that a DS # check that an unsigned reply is OK, by finding a secure proof that a DS
# record somewhere between the root and the domain does not exist. # record somewhere between the root and the domain does not exist.
# The cost of setting this is that even queries in unsigned domains will need # The cost of setting this is that even queries in unsigned domains will need
# one or more extra DNS queries to verify. # one or more extra DNS queries to verify.
#dnssec-check-unsigned #dnssec-check-unsigned
@ -183,11 +183,11 @@
#dhcp-range=1234::2, 1234::500, 64, 12h #dhcp-range=1234::2, 1234::500, 64, 12h
# Do Router Advertisements, BUT NOT DHCP for this subnet. # Do Router Advertisements, BUT NOT DHCP for this subnet.
#dhcp-range=1234::, ra-only #dhcp-range=1234::, ra-only
# Do Router Advertisements, BUT NOT DHCP for this subnet, also try and # Do Router Advertisements, BUT NOT DHCP for this subnet, also try and
# add names to the DNS for the IPv6 address of SLAAC-configured dual-stack # add names to the DNS for the IPv6 address of SLAAC-configured dual-stack
# hosts. Use the DHCPv4 lease to derive the name, network segment and # hosts. Use the DHCPv4 lease to derive the name, network segment and
# MAC address and assume that the host will also have an # MAC address and assume that the host will also have an
# IPv6 address calculated using the SLAAC alogrithm. # IPv6 address calculated using the SLAAC alogrithm.
#dhcp-range=1234::, ra-names #dhcp-range=1234::, ra-names
@ -210,9 +210,9 @@
#dhcp-range=1234::, ra-stateless, ra-names #dhcp-range=1234::, ra-stateless, ra-names
# Do router advertisements for all subnets where we're doing DHCPv6 # Do router advertisements for all subnets where we're doing DHCPv6
# Unless overriden by ra-stateless, ra-names, et al, the router # Unless overriden by ra-stateless, ra-names, et al, the router
# advertisements will have the M and O bits set, so that the clients # advertisements will have the M and O bits set, so that the clients
# get addresses and configuration from DHCPv6, and the A bit reset, so the # get addresses and configuration from DHCPv6, and the A bit reset, so the
# clients don't use SLAAC addresses. # clients don't use SLAAC addresses.
#enable-ra #enable-ra
@ -278,11 +278,11 @@
# any machine with Ethernet address starting 11:22:33: # any machine with Ethernet address starting 11:22:33:
#dhcp-host=11:22:33:*:*:*,set:red #dhcp-host=11:22:33:*:*:*,set:red
# Give a fixed IPv6 address and name to client with # Give a fixed IPv6 address and name to client with
# DUID 00:01:00:01:16:d2:83:fc:92:d4:19:e2:d8:b2 # DUID 00:01:00:01:16:d2:83:fc:92:d4:19:e2:d8:b2
# Note the MAC addresses CANNOT be used to identify DHCPv6 clients. # Note the MAC addresses CANNOT be used to identify DHCPv6 clients.
# Note also the they [] around the IPv6 address are obilgatory. # Note also the they [] around the IPv6 address are obilgatory.
#dhcp-host=id:00:01:00:01:16:d2:83:fc:92:d4:19:e2:d8:b2, fred, [1234::5] #dhcp-host=id:00:01:00:01:16:d2:83:fc:92:d4:19:e2:d8:b2, fred, [1234::5]
# Ignore any clients which are not specified in dhcp-host lines # Ignore any clients which are not specified in dhcp-host lines
# or /etc/ethers. Equivalent to ISC "deny unknown-clients". # or /etc/ethers. Equivalent to ISC "deny unknown-clients".
@ -338,7 +338,7 @@
# Send DHCPv6 option. Note [] around IPv6 addresses. # Send DHCPv6 option. Note [] around IPv6 addresses.
#dhcp-option=option6:dns-server,[1234::77],[1234::88] #dhcp-option=option6:dns-server,[1234::77],[1234::88]
# Send DHCPv6 option for namservers as the machine running # Send DHCPv6 option for namservers as the machine running
# dnsmasq and another. # dnsmasq and another.
#dhcp-option=option6:dns-server,[::],[1234::88] #dhcp-option=option6:dns-server,[::],[1234::88]
@ -645,4 +645,4 @@
#conf-dir=/etc/dnsmasq.d,.bak #conf-dir=/etc/dnsmasq.d,.bak
# Include all files in a directory which end in .conf # Include all files in a directory which end in .conf
#conf-dir=/etc/dnsmasq.d/*.conf #conf-dir=/etc/dnsmasq.d/*.conf

1
advanced/index.js Normal file
View file

@ -0,0 +1 @@
var x = "Pi-hole: A black hole for Internet advertisements."

View file

@ -14,7 +14,7 @@ server.modules = (
"mod_accesslog", "mod_accesslog",
"mod_expire", "mod_expire",
"mod_compress", "mod_compress",
"mod_redirect", "mod_redirect",
"mod_setenv", "mod_setenv",
"mod_rewrite" "mod_rewrite"
) )
@ -46,11 +46,16 @@ include_shell "/usr/share/lighttpd/include-conf-enabled.pl"
# If the URL starts with /admin, it is the Web interface # If the URL starts with /admin, it is the Web interface
$HTTP["url"] =~ "^/admin/" { $HTTP["url"] =~ "^/admin/" {
# Create a response header for debugging using curl -I # Create a response header for debugging using curl -I
setenv.add-response-header = ( "X-Pi-hole" => "The Pi-hole Web interface is working!" ) setenv.add-response-header = (
"X-Pi-hole" => "The Pi-hole Web interface is working!",
"X-Frame-Options" => "DENY"
)
} }
# If the URL does not start with /admin, then it is a query for an ad domain # If the URL does not start with /admin, then it is a query for an ad domain
$HTTP["url"] =~ "^(?!/admin)/.*" { $HTTP["url"] =~ "^(?!/admin)/.*" {
# Create a response header for debugging using curl -I # Create a response header for debugging using curl -I
setenv.add-response-header = ( "X-Pi-hole" => "A black hole for Internet advertisements." ) setenv.add-response-header = ( "X-Pi-hole" => "A black hole for Internet advertisements." )
# rewrite only js requests
url.rewrite = ("(.*).js" => "pihole/index.js")
} }

View file

@ -0,0 +1,77 @@
# Pi-hole: A black hole for Internet advertisements
# (c) 2015, 2016 by Jacob Salmela
# Network-wide ad blocking via your Raspberry Pi
# http://pi-hole.net
# lighttpd config for Pi-hole
#
# Pi-hole is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
server.modules = (
"mod_access",
"mod_fastcgi",
"mod_accesslog",
"mod_expire",
"mod_compress",
"mod_redirect",
"mod_setenv",
"mod_rewrite"
)
server.document-root = "/var/www/html"
server.error-handler-404 = "pihole/index.html"
server.upload-dirs = ( "/var/cache/lighttpd/uploads" )
server.errorlog = "/var/log/lighttpd/error.log"
server.pid-file = "/var/run/lighttpd.pid"
server.username = "lighttpd"
server.groupname = "lighttpd"
server.port = 80
accesslog.filename = "/var/log/lighttpd/access.log"
accesslog.format = "%{%s}t|%V|%r|%s|%b"
index-file.names = ( "index.php", "index.html", "index.lighttpd.html" )
url.access-deny = ( "~", ".inc" )
static-file.exclude-extensions = ( ".php", ".pl", ".fcgi" )
compress.cache-dir = "/var/cache/lighttpd/compress/"
compress.filetype = ( "application/javascript", "text/css", "text/html", "text/plain" )
mimetype.assign = ( ".png" => "image/png",
".jpg" => "image/jpeg",
".jpeg" => "image/jpeg",
".html" => "text/html",
".css" => "text/css; charset=utf-8",
".js" => "application/javascript",
".json" => "application/json",
".txt" => "text/plain" )
# default listening port for IPv6 falls back to the IPv4 port
#include_shell "/usr/share/lighttpd/use-ipv6.pl " + server.port
#include_shell "/usr/share/lighttpd/create-mime.assign.pl"
#include_shell "/usr/share/lighttpd/include-conf-enabled.pl"
fastcgi.server = ( ".php" =>
( "localhost" =>
(
"socket" => "/tmp/php-fastcgi.socket",
"bin-path" => "/usr/bin/php-cgi"
)
)
)
# If the URL starts with /admin, it is the Web interface
$HTTP["url"] =~ "^/admin/" {
# Create a response header for debugging using curl -I
setenv.add-response-header = ( "X-Pi-hole" => "The Pi-hole Web interface is working!" )
}
# If the URL does not start with /admin, then it is a query for an ad domain
$HTTP["url"] =~ "^(?!/admin)/.*" {
# Create a response header for debugging using curl -I
setenv.add-response-header = ( "X-Pi-hole" => "A black hole for Internet advertisements." )
# rewrite only js requests
url.rewrite = ("(.*).js" => "pihole/index.js")
}

View file

@ -10,17 +10,17 @@
# (at your option) any later version. # (at your option) any later version.
# Pi-hole: Update the ad sources once a week on Sunday at 01:59 # Pi-hole: Update the ad sources once a week on Sunday at 01:59
# Download any updates from the ad lists # Download any updates from the adlists
59 1 * * 7 root /usr/local/bin/gravity.sh 59 1 * * 7 root /usr/local/bin/pihole updateGravity
# Pi-hole: Update the Web interface shortly after gravity runs # Pi-hole: Update the Web interface shortly after gravity runs
# This should also update the version number if it is changed in the dashboard repo # This should also update the version number if it is changed in the dashboard repo
30 2 * * 7 root /usr/local/bin/updateDashboard.sh 30 2 * * 7 root /usr/local/bin/pihole updateDashboard
# Pi-hole: Parse the log file before it is flushed and save the stats to a database # Pi-hole: Parse the log file before it is flushed and save the stats to a database
# This will be used for a historical view of your Pi-hole's performance # This will be used for a historical view of your Pi-hole's performance
#50 23 * * * root /usr/local/bin/dailyLog.sh #50 23 * * * root /usr/local/bin/dailyLog.sh # note: this is outdated
# Pi-hole: Flush the log daily at 11:58 so it doesn't get out of control # Pi-hole: Flush the log daily at 11:58 so it doesn't get out of control
# Stats will be viewable in the Web interface thanks to the cron job above # Stats will be viewable in the Web interface thanks to the cron job above
58 23 * * * root /usr/local/bin/piholeLogFlush.sh 58 23 * * * root /usr/local/bin/pihole flush

12
advanced/pihole.sudo Normal file
View file

@ -0,0 +1,12 @@
# Pi-hole: A black hole for Internet advertisements
# (c) 2015, 2016 by Jacob Salmela
# Network-wide ad blocking via your Raspberry Pi
# http://pi-hole.net
# Allows the WebUI to use Pi-hole commands
#
# Pi-hole is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
www-data ALL=NOPASSWD: /usr/local/bin/pihole

View file

@ -0,0 +1,87 @@
module pihole 1.0;
require {
type var_log_t;
type unconfined_t;
type init_t;
type auditd_t;
type syslogd_t;
type NetworkManager_t;
type mdadm_t;
type tuned_t;
type avahi_t;
type irqbalance_t;
type system_dbusd_t;
type kernel_t;
type httpd_sys_script_t;
type systemd_logind_t;
type httpd_t;
type policykit_t;
type dnsmasq_t;
type udev_t;
type postfix_pickup_t;
type sshd_t;
type crond_t;
type getty_t;
type lvm_t;
type postfix_qmgr_t;
type postfix_master_t;
class dir { getattr search };
class file { read open setattr };
}
#============= dnsmasq_t ==============
allow dnsmasq_t var_log_t:file { open setattr };
#============= httpd_t ==============
allow httpd_t var_log_t:file { read open };
#============= httpd_sys_script_t (class: dir) ==============
allow httpd_sys_script_t NetworkManager_t:dir { getattr search };
allow httpd_sys_script_t auditd_t:dir { getattr search };
allow httpd_sys_script_t avahi_t:dir { getattr search };
allow httpd_sys_script_t crond_t:dir { getattr search };
allow httpd_sys_script_t dnsmasq_t:dir { getattr search };
allow httpd_sys_script_t getty_t:dir { getattr search };
allow httpd_sys_script_t httpd_t:dir { getattr search };
allow httpd_sys_script_t init_t:dir { getattr search };
allow httpd_sys_script_t irqbalance_t:dir { getattr search };
allow httpd_sys_script_t kernel_t:dir { getattr search };
allow httpd_sys_script_t lvm_t:dir { getattr search };
allow httpd_sys_script_t mdadm_t:dir { getattr search };
allow httpd_sys_script_t policykit_t:dir { getattr search };
allow httpd_sys_script_t postfix_master_t:dir { getattr search };
allow httpd_sys_script_t postfix_pickup_t:dir { getattr search };
allow httpd_sys_script_t postfix_qmgr_t:dir { getattr search };
allow httpd_sys_script_t sshd_t:dir { getattr search };
allow httpd_sys_script_t syslogd_t:dir { getattr search };
allow httpd_sys_script_t system_dbusd_t:dir { getattr search };
allow httpd_sys_script_t systemd_logind_t:dir { getattr search };
allow httpd_sys_script_t tuned_t:dir { getattr search };
allow httpd_sys_script_t udev_t:dir { getattr search };
allow httpd_sys_script_t unconfined_t:dir { getattr search };
#============= httpd_sys_script_t (class: file) ==============
allow httpd_sys_script_t NetworkManager_t:file { read open };
allow httpd_sys_script_t auditd_t:file { read open };
allow httpd_sys_script_t avahi_t:file { read open };
allow httpd_sys_script_t crond_t:file { read open };
allow httpd_sys_script_t dnsmasq_t:file { read open };
allow httpd_sys_script_t getty_t:file { read open };
allow httpd_sys_script_t httpd_t:file { read open };
allow httpd_sys_script_t init_t:file { read open };
allow httpd_sys_script_t irqbalance_t:file { read open };
allow httpd_sys_script_t kernel_t:file { read open };
allow httpd_sys_script_t lvm_t:file { read open };
allow httpd_sys_script_t mdadm_t:file { read open };
allow httpd_sys_script_t policykit_t:file { read open };
allow httpd_sys_script_t postfix_master_t:file { read open };
allow httpd_sys_script_t postfix_pickup_t:file { read open };
allow httpd_sys_script_t postfix_qmgr_t:file { read open };
allow httpd_sys_script_t sshd_t:file { read open };
allow httpd_sys_script_t syslogd_t:file { read open };
allow httpd_sys_script_t system_dbusd_t:file { read open };
allow httpd_sys_script_t systemd_logind_t:file { read open };
allow httpd_sys_script_t tuned_t:file { read open };
allow httpd_sys_script_t udev_t:file { read open };
allow httpd_sys_script_t unconfined_t:file { read open };

View file

@ -36,16 +36,6 @@ columns=$(tput cols)
r=$(( rows / 2 )) r=$(( rows / 2 ))
c=$(( columns / 2 )) c=$(( columns / 2 ))
# Find IP used to route to outside world
IPv4dev=$(ip route get 8.8.8.8 | awk '{for(i=1;i<=NF;i++)if($i~/dev/)print $(i+1)}')
IPv4addr=$(ip -o -f inet addr show dev $IPv4dev | awk '{print $4}' | awk 'END {print}')
IPv4gw=$(ip route get 8.8.8.8 | awk '{print $3}')
availableInterfaces=$(ip -o link | awk '{print $2}' | grep -v "lo" | cut -d':' -f1)
dhcpcdFile=/etc/dhcpcd.conf
######## FIRST CHECK ######## ######## FIRST CHECK ########
# Must be root to install # Must be root to install
echo ":::" echo ":::"
@ -55,36 +45,78 @@ else
echo "::: sudo will be used for the install." echo "::: sudo will be used for the install."
# Check if it is actually installed # Check if it is actually installed
# If it isn't, exit because the install cannot complete # If it isn't, exit because the install cannot complete
if [[ $(dpkg-query -s sudo) ]];then if [ -x "$(command -v sudo)" ];then
export SUDO="sudo" export SUDO="sudo"
else else
echo "::: Please install sudo or run this as root." echo "::: sudo is needed for the Web interface to run pihole commands. Please run this script as root and it will be automatically installed."
exit 1 exit 1
fi fi
fi fi
# Compatability
if [ -d "/etc/pihole" ]; then if [ -x "$(command -v rpm)" ];then
# Likely an existing install # Fedora Family
upgrade=true if [ -x "$(command -v dnf)" ];then
PKG_MANAGER="dnf"
else else
upgrade=false PKG_MANAGER="yum"
fi
PKG_CACHE="/var/cache/$PKG_MANAGER"
UPDATE_PKG_CACHE="$PKG_MANAGER check-update -q"
PKG_UPDATE="$PKG_MANAGER update -y"
PKG_INSTALL="$PKG_MANAGER install -y"
PKG_COUNT="$PKG_MANAGER check-update | grep -v ^Last | grep -c ^[a-zA-Z0-9]"
INSTALLER_DEPS=( iproute net-tools procps-ng newt )
PIHOLE_DEPS=( epel-release bind-utils bc dnsmasq lighttpd lighttpd-fastcgi php-common php-cli php git curl unzip wget findutils cronie sudo nmap-ncat )
LIGHTTPD_USER="lighttpd"
LIGHTTPD_GROUP="lighttpd"
LIGHTTPD_CFG="lighttpd.conf.fedora"
package_check() {
rpm -qa | grep ^$1- > /dev/null
}
elif [ -x "$(command -v apt-get)" ];then
# Debian Family
PKG_MANAGER="apt-get"
PKG_CACHE="/var/cache/apt"
UPDATE_PKG_CACHE="$PKG_MANAGER -qq update"
PKG_UPDATE="$PKG_MANAGER upgrade"
PKG_INSTALL="$PKG_MANAGER --yes --quiet install"
PKG_COUNT="$PKG_MANAGER -s -o Debug::NoLocking=true upgrade | grep -c ^Inst"
INSTALLER_DEPS=( apt-utils whiptail dhcpcd5)
PIHOLE_DEPS=( dnsutils bc dnsmasq lighttpd php5-common php5-cgi php5 git curl unzip wget sudo netcat )
LIGHTTPD_USER="www-data"
LIGHTTPD_GROUP="www-data"
LIGHTTPD_CFG="lighttpd.conf.debian"
package_check() {
dpkg-query -W -f='${Status}' "$1" 2>/dev/null | grep -c "ok installed"
}
else
echo "OS distribution not supported"
exit
fi fi
####### FUNCTIONS ########## ####### FUNCTIONS ##########
###All credit for the below function goes to http://fitnr.com/showing-a-bash-spinner.html spinner()
spinner() { {
local pid=$1 local pid=$1
local delay=0.50
local spinstr='/-\|'
while [ "$(ps a | awk '{print $1}' | grep "$pid")" ]; do
local temp=${spinstr#?}
printf " [%c] " "$spinstr"
local spinstr=$temp${spinstr%"$temp"}
sleep $delay
printf "\b\b\b\b\b\b"
done
printf " \b\b\b\b"
}
spin='-\|/' findIPRoute() {
i=0 # Find IP used to route to outside world
while $SUDO kill -0 $pid 2>/dev/null IPv4dev=$(ip route get 8.8.8.8 | awk '{for(i=1;i<=NF;i++)if($i~/dev/)print $(i+1)}')
do IPv4addr=$(ip -o -f inet addr show dev "$IPv4dev" | awk '{print $4}' | awk 'END {print}')
i=$(( (i+1) %4 )) IPv4gw=$(ip route get 8.8.8.8 | awk '{print $3}')
printf "\b${spin:$i:1}" availableInterfaces=$(ip -o link | awk '{print $2}' | grep -v "lo" | cut -d':' -f1 | cut -d'@' -f1)
sleep .1
done
printf "\b"
} }
backupLegacyPihole() { backupLegacyPihole() {
@ -92,12 +124,17 @@ backupLegacyPihole() {
if [[ -f /etc/dnsmasq.d/adList.conf ]];then if [[ -f /etc/dnsmasq.d/adList.conf ]];then
echo "::: Original Pi-hole detected. Initiating sub space transport" echo "::: Original Pi-hole detected. Initiating sub space transport"
$SUDO mkdir -p /etc/pihole/original/ $SUDO mkdir -p /etc/pihole/original/
$SUDO mv /etc/dnsmasq.d/adList.conf /etc/pihole/original/adList.conf.$(date "+%Y-%m-%d") $SUDO mv /etc/dnsmasq.d/adList.conf /etc/pihole/original/adList.conf."$(date "+%Y-%m-%d")"
$SUDO mv /etc/dnsmasq.conf /etc/pihole/original/dnsmasq.conf.$(date "+%Y-%m-%d") $SUDO mv /etc/dnsmasq.conf /etc/pihole/original/dnsmasq.conf."$(date "+%Y-%m-%d")"
$SUDO mv /etc/resolv.conf /etc/pihole/original/resolv.conf.$(date "+%Y-%m-%d") $SUDO mv /etc/resolv.conf /etc/pihole/original/resolv.conf."$(date "+%Y-%m-%d")"
$SUDO mv /etc/lighttpd/lighttpd.conf /etc/pihole/original/lighttpd.conf.$(date "+%Y-%m-%d") $SUDO mv /etc/lighttpd/lighttpd.conf /etc/pihole/original/lighttpd.conf."$(date "+%Y-%m-%d")"
$SUDO mv /var/www/pihole/index.html /etc/pihole/original/index.html.$(date "+%Y-%m-%d") $SUDO mv /var/www/pihole/index.html /etc/pihole/original/index.html."$(date "+%Y-%m-%d")"
$SUDO mv /usr/local/bin/gravity.sh /etc/pihole/original/gravity.sh.$(date "+%Y-%m-%d") if [ ! -d /opt/pihole ]; then
$SUDO mkdir /opt/pihole
$SUDO chown "$USER":root /opt/pihole
$SUDO chmod u+srwx /opt/pihole
fi
$SUDO mv /opt/pihole/gravity.sh /etc/pihole/original/gravity.sh."$(date "+%Y-%m-%d")"
else else
: :
fi fi
@ -111,10 +148,30 @@ welcomeDialogs() {
whiptail --msgbox --backtitle "Plea" --title "Free and open source" "The Pi-hole is free, but powered by your donations: http://pi-hole.net/donate" $r $c whiptail --msgbox --backtitle "Plea" --title "Free and open source" "The Pi-hole is free, but powered by your donations: http://pi-hole.net/donate" $r $c
# Explain the need for a static address # Explain the need for a static address
whiptail --msgbox --backtitle "Initating network interface" --title "Static IP Needed" "The Pi-hole is a SERVER so it needs a STATIC IP ADDRESS to function properly. whiptail --msgbox --backtitle "Initating network interface" --title "Static IP Needed" "The Pi-hole is a SERVER so it needs a STATIC IP ADDRESS to function properly.
In the next section, you can choose to use your current network settings (DHCP) or to manually edit them." $r $c
In the next section, you can choose to use your current network settings (DHCP) or to manually edit them." $r $c
} }
verifyFreeDiskSpace() {
# 50MB is the minimum space needed (45MB install (includes web admin bootstrap/jquery libraries etc) + 5MB one day of logs.)
requiredFreeBytes=51200
existingFreeBytes=$(df -lk / 2>&1 | awk '{print $4}' | head -2 | tail -1)
if ! [[ "$existingFreeBytes" =~ ^([0-9])+$ ]]; then
existingFreeBytes=$(df -lk /dev 2>&1 | awk '{print $4}' | head -2 | tail -1)
fi
if [[ $existingFreeBytes -lt $requiredFreeBytes ]]; then
whiptail --msgbox --backtitle "Insufficient Disk Space" --title "Insufficient Disk Space" "\nYour system appears to be low on disk space. pi-hole recomends a minimum of $requiredFreeBytes Bytes.\nYou only have $existingFreeBytes Free.\n\nIf this is a new install you may need to expand your disk.\n\nTry running:\n 'sudo raspi-config'\nChoose the 'expand file system option'\n\nAfter rebooting, run this installation again.\n\ncurl -L install.pi-hole.net | bash\n" $r $c
echo "$existingFreeBytes is less than $requiredFreeBytes"
echo "Insufficient free space, exiting..."
exit 1
fi
}
chooseInterface() { chooseInterface() {
# Turn the available interfaces into an array so it can be used with a whiptail dialog # Turn the available interfaces into an array so it can be used with a whiptail dialog
interfacesArray=() interfacesArray=()
@ -134,24 +191,30 @@ chooseInterface() {
interfaceCount=$(echo "$availableInterfaces" | wc -l) interfaceCount=$(echo "$availableInterfaces" | wc -l)
chooseInterfaceCmd=(whiptail --separate-output --radiolist "Choose An Interface" $r $c $interfaceCount) chooseInterfaceCmd=(whiptail --separate-output --radiolist "Choose An Interface" $r $c $interfaceCount)
chooseInterfaceOptions=$("${chooseInterfaceCmd[@]}" "${interfacesArray[@]}" 2>&1 >/dev/tty) chooseInterfaceOptions=$("${chooseInterfaceCmd[@]}" "${interfacesArray[@]}" 2>&1 >/dev/tty)
if [[ $? = 0 ]];then if [[ $? = 0 ]]; then
for desiredInterface in $chooseInterfaceOptions for desiredInterface in $chooseInterfaceOptions
do do
piholeInterface=$desiredInterface piholeInterface=$desiredInterface
echo "::: Using interface: $piholeInterface" echo "::: Using interface: $piholeInterface"
echo ${piholeInterface} > /tmp/piholeINT echo "${piholeInterface}" > /tmp/piholeINT
done done
else else
echo "::: Cancel selected, exiting...." echo "::: Cancel selected, exiting...."
exit 1 exit 1
fi fi
} }
cleanupIPv6() {
# Removes IPv6 indicator file if we are not using IPv6
if [ -f "/etc/pihole/.useIPv6" ] && [ ! "$useIPv6" ]; then
rm /etc/pihole/.useIPv6
fi
}
use4andor6() { use4andor6() {
# Let use select IPv4 and/or IPv6 # Let use select IPv4 and/or IPv6
cmd=(whiptail --separate-output --checklist "Select Protocols" $r $c 2) cmd=(whiptail --separate-output --checklist "Select Protocols (press space to select)" $r $c 2)
options=(IPv4 "Block ads over IPv4" on options=(IPv4 "Block ads over IPv4" on
IPv6 "Block ads over IPv6" off) IPv6 "Block ads over IPv6" off)
choices=$("${cmd[@]}" "${options[@]}" 2>&1 >/dev/tty) choices=$("${cmd[@]}" "${options[@]}" 2>&1 >/dev/tty)
@ -159,11 +222,11 @@ use4andor6() {
for choice in $choices for choice in $choices
do do
case $choice in case $choice in
IPv4 ) useIPv4=true;; IPv4 ) useIPv4=true;;
IPv6 ) useIPv6=true;; IPv6 ) useIPv6=true;;
esac esac
done done
if [ $useIPv4 ] && [ ! $useIPv6 ]; then if [ $useIPv4 ] && [ ! $useIPv6 ]; then
getStaticIPv4Settings getStaticIPv4Settings
setStaticIPv4 setStaticIPv4
@ -187,6 +250,7 @@ use4andor6() {
echo "::: Exiting" echo "::: Exiting"
exit 1 exit 1
fi fi
cleanupIPv6
else else
echo "::: Cancel selected. Exiting..." echo "::: Cancel selected. Exiting..."
exit 1 exit 1
@ -204,12 +268,14 @@ useIPv6dialog() {
getStaticIPv4Settings() { getStaticIPv4Settings() {
# Ask if the user wants to use DHCP settings as their static IP # Ask if the user wants to use DHCP settings as their static IP
if (whiptail --backtitle "Calibrating network interface" --title "Static IP Address" --yesno "Do you want to use your current network settings as a static address? if (whiptail --backtitle "Calibrating network interface" --title "Static IP Address" --yesno "Do you want to use your current network settings as a static address?
IP address: $IPv4addr IP address: $IPv4addr
Gateway: $IPv4gw" $r $c) then Gateway: $IPv4gw" $r $c) then
# If they choose yes, let the user know that the IP address will not be available via DHCP and may cause a conflict. # If they choose yes, let the user know that the IP address will not be available via DHCP and may cause a conflict.
whiptail --msgbox --backtitle "IP information" --title "FYI: IP Conflict" "It is possible your router could still try to assign this IP to a device, which would cause a conflict. But in most cases the router is smart enough to not do that. whiptail --msgbox --backtitle "IP information" --title "FYI: IP Conflict" "It is possible your router could still try to assign this IP to a device, which would cause a conflict. But in most cases the router is smart enough to not do that.
If you are worried, either manually set the address, or modify the DHCP reservation pool so it does not include the IP you want. If you are worried, either manually set the address, or modify the DHCP reservation pool so it does not include the IP you want.
It is also possible to use a DHCP reservation, but if you are going to do that, you might as well set a static address." $r $c It is also possible to use a DHCP reservation, but if you are going to do that, you might as well set a static address." $r $c
#piholeIP is saved to a permanent file so gravity.sh can use it when updating
$SUDO echo "${IPv4addr%/*}" > /etc/pihole/piholeIP
# Nothing else to do since the variables are already set above # Nothing else to do since the variables are already set above
else else
# Otherwise, we need to ask the user to input their desired settings. # Otherwise, we need to ask the user to input their desired settings.
@ -218,84 +284,200 @@ getStaticIPv4Settings() {
until [[ $ipSettingsCorrect = True ]] until [[ $ipSettingsCorrect = True ]]
do do
# Ask for the IPv4 address # Ask for the IPv4 address
IPv4addr=$(whiptail --backtitle "Calibrating network interface" --title "IPv4 address" --inputbox "Enter your desired IPv4 address" $r $c $IPv4addr 3>&1 1>&2 2>&3) IPv4addr=$(whiptail --backtitle "Calibrating network interface" --title "IPv4 address" --inputbox "Enter your desired IPv4 address" $r $c "$IPv4addr" 3>&1 1>&2 2>&3)
if [[ $? = 0 ]];then if [[ $? = 0 ]];then
echo "::: Your static IPv4 address: $IPv4addr" echo "::: Your static IPv4 address: $IPv4addr"
# Ask for the gateway # Ask for the gateway
IPv4gw=$(whiptail --backtitle "Calibrating network interface" --title "IPv4 gateway (router)" --inputbox "Enter your desired IPv4 default gateway" $r $c $IPv4gw 3>&1 1>&2 2>&3) IPv4gw=$(whiptail --backtitle "Calibrating network interface" --title "IPv4 gateway (router)" --inputbox "Enter your desired IPv4 default gateway" $r $c "$IPv4gw" 3>&1 1>&2 2>&3)
if [[ $? = 0 ]];then if [[ $? = 0 ]];then
echo "::: Your static IPv4 gateway: $IPv4gw" echo "::: Your static IPv4 gateway: $IPv4gw"
# Give the user a chance to review their settings before moving on # Give the user a chance to review their settings before moving on
if (whiptail --backtitle "Calibrating network interface" --title "Static IP Address" --yesno "Are these settings correct? if (whiptail --backtitle "Calibrating network interface" --title "Static IP Address" --yesno "Are these settings correct?
IP address: $IPv4addr IP address: $IPv4addr
Gateway: $IPv4gw" $r $c)then Gateway: $IPv4gw" $r $c)then
# If the settings are correct, then we need to set the piholeIP # If the settings are correct, then we need to set the piholeIP
# Saving it to a temporary file us to retrieve it later when we run the gravity.sh script # Saving it to a temporary file us to retrieve it later when we run the gravity.sh script. piholeIP is saved to a permanent file so gravity.sh can use it when updating
echo ${IPv4addr%/*} > /tmp/piholeIP $SUDO echo "${IPv4addr%/*}" > /etc/pihole/piholeIP
echo $piholeInterface > /tmp/piholeINT $SUDO echo "$piholeInterface" > /tmp/piholeINT
# After that's done, the loop ends and we move on # After that's done, the loop ends and we move on
ipSettingsCorrect=True ipSettingsCorrect=True
else
# If the settings are wrong, the loop continues
ipSettingsCorrect=False
fi
else else
# Cancelling gateway settings window # If the settings are wrong, the loop continues
ipSettingsCorrect=False ipSettingsCorrect=False
echo "::: Cancel selected. Exiting..."
exit 1
fi fi
else else
# Cancelling IPv4 settings window # Cancelling gateway settings window
ipSettingsCorrect=False ipSettingsCorrect=False
echo "::: Cancel selected. Exiting..." echo "::: Cancel selected. Exiting..."
exit 1 exit 1
fi fi
else
# Cancelling IPv4 settings window
ipSettingsCorrect=False
echo "::: Cancel selected. Exiting..."
exit 1
fi
done done
# End the if statement for DHCP vs. static # End the if statement for DHCP vs. static
fi fi
} }
setDHCPCD() { setDHCPCD() {
# Append these lines to dhcpcd.conf to enable a static IP # Append these lines to dhcpcd.conf to enable a static IP
echo "::: interface $piholeInterface echo "## interface $piholeInterface
static ip_address=$IPv4addr static ip_address=$IPv4addr
static routers=$IPv4gw static routers=$IPv4gw
static domain_name_servers=$IPv4gw" | $SUDO tee -a $dhcpcdFile >/dev/null static domain_name_servers=$IPv4gw" | $SUDO tee -a /etc/dhcpcd.conf >/dev/null
} }
setStaticIPv4() { setStaticIPv4() {
# Tries to set the IPv4 address if [[ -f /etc/dhcpcd.conf ]];then
if grep -q $IPv4addr $dhcpcdFile; then # Debian Family
# address already set, noop if grep -q "$IPv4addr" /etc/dhcpcd.conf; then
: echo "::: Static IP already configured"
else
setDHCPCD
$SUDO ip addr replace dev "$piholeInterface" "$IPv4addr"
echo ":::"
echo "::: Setting IP to $IPv4addr. You may need to restart after the install is complete."
echo ":::"
fi
elif [[ -f /etc/sysconfig/network-scripts/ifcfg-$piholeInterface ]];then
# Fedora Family
IFCFG_FILE=/etc/sysconfig/network-scripts/ifcfg-$piholeInterface
if grep -q "$IPv4addr" $IFCFG_FILE; then
echo "::: Static IP already configured"
else
IPADDR=$(echo $IPv4addr | cut -f1 -d/)
CIDR=$(echo $IPv4addr | cut -f2 -d/)
# Backup existing interface configuration:
cp $IFCFG_FILE $IFCFG_FILE.backup-$(date +%Y-%m-%d-%H%M%S)
# Build Interface configuration file:
$SUDO echo "# Configured via Pi-Hole installer" > $IFCFG_FILE
$SUDO echo "DEVICE=$piholeInterface" >> $IFCFG_FILE
$SUDO echo "BOOTPROTO=none" >> $IFCFG_FILE
$SUDO echo "ONBOOT=yes" >> $IFCFG_FILE
$SUDO echo "IPADDR=$IPADDR" >> $IFCFG_FILE
$SUDO echo "PREFIX=$CIDR" >> $IFCFG_FILE
$SUDO echo "USERCTL=no" >> $IFCFG_FILE
$SUDO ip addr replace dev "$piholeInterface" "$IPv4addr"
if [ -x "$(command -v nmcli)" ];then
# Tell NetworkManager to read our new sysconfig file
$SUDO nmcli con load $IFCFG_FILE > /dev/null
fi
echo ":::"
echo "::: Setting IP to $IPv4addr. You may need to restart after the install is complete."
echo ":::"
fi
else else
setDHCPCD echo "::: Warning: Unable to locate configuration file to set static IPv4 address!"
$SUDO ip addr replace dev $piholeInterface $IPv4addr exit 1
echo ":::"
echo "::: Setting IP to $IPv4addr. You may need to restart after the install is complete."
echo ":::"
fi fi
} }
function valid_ip()
{
local ip=$1
local stat=1
if [[ $ip =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then
OIFS=$IFS
IFS='.'
ip=($ip)
IFS=$OIFS
[[ ${ip[0]} -le 255 && ${ip[1]} -le 255 \
&& ${ip[2]} -le 255 && ${ip[3]} -le 255 ]]
stat=$?
fi
return $stat
}
setDNS(){ setDNS(){
DNSChoseCmd=(whiptail --separate-output --radiolist "Select Upstream DNS Provider" $r $c 2) DNSChoseCmd=(whiptail --separate-output --radiolist "Select Upstream DNS Provider. To use your own, select Custom." $r $c 6)
DNSChooseOptions=(Google "" on DNSChooseOptions=(Google "" on
OpenDNS "" off) OpenDNS "" off
Level3 "" off
Norton "" off
Comodo "" off
Custom "" off)
DNSchoices=$("${DNSChoseCmd[@]}" "${DNSChooseOptions[@]}" 2>&1 >/dev/tty) DNSchoices=$("${DNSChoseCmd[@]}" "${DNSChooseOptions[@]}" 2>&1 >/dev/tty)
if [[ $? = 0 ]];then if [[ $? = 0 ]];then
case $DNSchoices in case $DNSchoices in
Google) Google)
echo "::: Using Google DNS servers." echo "::: Using Google DNS servers."
piholeDNS1="8.8.8.8" piholeDNS1="8.8.8.8"
piholeDNS2="8.8.4.4" piholeDNS2="8.8.4.4"
;; ;;
OpenDNS) OpenDNS)
echo "::: Using OpenDNS servers." echo "::: Using OpenDNS servers."
piholeDNS1="208.67.222.222" piholeDNS1="208.67.222.222"
piholeDNS2="208.67.220.220" piholeDNS2="208.67.220.220"
;; ;;
esac Level3)
echo "::: Using Level3 servers."
piholeDNS1="4.2.2.1"
piholeDNS2="4.2.2.2"
;;
Norton)
echo "::: Using Norton ConnectSafe servers."
piholeDNS1="199.85.126.10"
piholeDNS2="199.85.127.10"
;;
Comodo)
echo "::: Using Comodo Secure servers."
piholeDNS1="8.26.56.26"
piholeDNS2="8.20.247.20"
;;
Custom)
until [[ $DNSSettingsCorrect = True ]]
do
strInvalid="Invalid"
if [ ! $piholeDNS1 ]; then
if [ ! $piholeDNS2 ]; then
prePopulate=""
else
prePopulate=", $piholeDNS2"
fi
elif [ $piholeDNS1 ] && [ ! $piholeDNS2 ]; then
prePopulate="$piholeDNS1"
elif [ $piholeDNS1 ] && [ $piholeDNS2 ]; then
prePopulate="$piholeDNS1, $piholeDNS2"
fi
piholeDNS=$(whiptail --backtitle "Specify Upstream DNS Provider(s)" --inputbox "Enter your desired upstream DNS provider(s), seperated by a comma.\n\nFor example '8.8.8.8, 8.8.4.4'" $r $c "$prePopulate" 3>&1 1>&2 2>&3)
if [[ $? = 0 ]];then
piholeDNS1=$(echo "$piholeDNS" | sed 's/[, \t]\+/,/g' | awk -F, '{print$1}')
piholeDNS2=$(echo "$piholeDNS" | sed 's/[, \t]\+/,/g' | awk -F, '{print$2}')
if ! valid_ip "$piholeDNS1" || [ ! "$piholeDNS1" ]; then
piholeDNS1=$strInvalid
fi
if ! valid_ip "$piholeDNS2" && [ "$piholeDNS2" ]; then
piholeDNS2=$strInvalid
fi
else
echo "::: Cancel selected, exiting...."
exit 1
fi
if [[ $piholeDNS1 == "$strInvalid" ]] || [[ $piholeDNS2 == "$strInvalid" ]]; then
whiptail --msgbox --backtitle "Invalid IP" --title "Invalid IP" "One or both entered IP addresses were invalid. Please try again.\n\n DNS Server 1: $piholeDNS1\n DNS Server 2: $piholeDNS2" $r $c
if [[ $piholeDNS1 == "$strInvalid" ]]; then
piholeDNS1=""
fi
if [[ $piholeDNS2 == "$strInvalid" ]]; then
piholeDNS2=""
fi
DNSSettingsCorrect=False
else
if (whiptail --backtitle "Specify Upstream DNS Provider(s)" --title "Upstream DNS Provider(s)" --yesno "Are these settings correct?\n DNS Server 1: $piholeDNS1\n DNS Server 2: $piholeDNS2" $r $c) then
DNSSettingsCorrect=True
else
# If the settings are wrong, the loop continues
DNSSettingsCorrect=False
fi
fi
done
;;
esac
else else
echo "::: Cancel selected. Exiting..." echo "::: Cancel selected. Exiting..."
exit 1 exit 1
@ -307,109 +489,150 @@ versionCheckDNSmasq(){
dnsFile1="/etc/dnsmasq.conf" dnsFile1="/etc/dnsmasq.conf"
dnsFile2="/etc/dnsmasq.conf.orig" dnsFile2="/etc/dnsmasq.conf.orig"
dnsSearch="addn-hosts=/etc/pihole/gravity.list" dnsSearch="addn-hosts=/etc/pihole/gravity.list"
defaultFile="/etc/.pihole/advanced/dnsmasq.conf.original"
# Check if /etc/dnsmasq.conf exists newFileToInstall="/etc/.pihole/advanced/01-pihole.conf"
if [ -d "/etc/dnsmasq.conf" ]; then newFileFinalLocation="/etc/dnsmasq.d/01-pihole.conf"
# If true, Check dnsmasq.conf for pihole magic
if [ -f $dnsFile1 ]; then
echo -n "::: Existing dnsmasq.conf found..."
if grep -q $dnsSearch $dnsFile1; then if grep -q $dnsSearch $dnsFile1; then
# If true, Check dnsmasq.conf.orig for pihole magic echo " it is from a previous pi-hole install."
if grep -q $dnsSearch $dnsFile2; then echo -n "::: Backing up dnsmasq.conf to dnsmasq.conf.orig..."
# If true, use advanced/dnsmasq.conf.original $SUDO mv -f $dnsFile1 $dnsFile2
$SUDO mv -f /etc/dnsmasq.conf /etc/dnsmasq.conf.orig echo " done."
$SUDO cp /etc/.pihole/advanced/dnsmasq.conf.original /etc/dnsmasq.conf echo -n "::: Restoring default dnsmasq.conf..."
else $SUDO cp $defaultFile $dnsFile1
# If false, mv original file back echo " done."
$SUDO mv -f /etc/dnsmasq.conf.orig /etc/dnsmasq.conf else
fi echo " it is not a pi-hole file, leaving alone!"
# If false, This is a fresh install
fi fi
else else
# If false, use advanced/dnsmasq.conf.original echo -n "::: No dnsmasq.conf found.. restoring default dnsmasq.conf..."
$SUDO cp /etc/.pihole/advanced/dnsmasq.conf.original /etc/dnsmasq.conf $SUDO cp $defaultFile $dnsFile1
echo " done."
fi fi
$SUDO cp /etc/.pihole/advanced/01-pihole.conf /etc/dnsmasq.d/01-pihole.conf echo -n "::: Copying 01-pihole.conf to /etc/dnsmasq.d/01-pihole.conf..."
$SUDO sed -i "s/@INT@/$piholeInterface/" /etc/dnsmasq.d/01-pihole.conf $SUDO cp $newFileToInstall $newFileFinalLocation
$SUDO sed -i "s/@DNS1@/$piholeDNS1/" /etc/dnsmasq.d/01-pihole.conf echo " done."
$SUDO sed -i "s/@DNS2@/$piholeDNS2/" /etc/dnsmasq.d/01-pihole.conf $SUDO sed -i "s/@INT@/$piholeInterface/" $newFileFinalLocation
if [[ "$piholeDNS1" != "" ]]; then
$SUDO sed -i "s/@DNS1@/$piholeDNS1/" $newFileFinalLocation
else
$SUDO sed -i '/^server=@DNS1@/d' $newFileFinalLocation
fi
if [[ "$piholeDNS2" != "" ]]; then
$SUDO sed -i "s/@DNS2@/$piholeDNS2/" $newFileFinalLocation
else
$SUDO sed -i '/^server=@DNS2@/d' $newFileFinalLocation
fi
$SUDO sed -i 's/^#conf-dir=\/etc\/dnsmasq.d$/conf-dir=\/etc\/dnsmasq.d/' $dnsFile1
} }
installScripts() { installScripts() {
# Install the scripts from /etc/.pihole to their various locations # Install the scripts from /etc/.pihole to their various locations
$SUDO echo ":::" $SUDO echo ":::"
$SUDO echo -n "::: Installing scripts..." $SUDO echo -n "::: Installing scripts to /opt/pihole..."
$SUDO cp /etc/.pihole/gravity.sh /usr/local/bin/gravity.sh if [ ! -d /opt/pihole ]; then
$SUDO cp /etc/.pihole/advanced/Scripts/chronometer.sh /usr/local/bin/chronometer.sh $SUDO mkdir /opt/pihole
$SUDO cp /etc/.pihole/advanced/Scripts/whitelist.sh /usr/local/bin/whitelist.sh $SUDO chown "$USER":root /opt/pihole
$SUDO cp /etc/.pihole/advanced/Scripts/blacklist.sh /usr/local/bin/blacklist.sh $SUDO chmod u+srwx /opt/pihole
$SUDO cp /etc/.pihole/advanced/Scripts/piholeLogFlush.sh /usr/local/bin/piholeLogFlush.sh fi
$SUDO cp /etc/.pihole/advanced/Scripts/updateDashboard.sh /usr/local/bin/updateDashboard.sh $SUDO cp /etc/.pihole/gravity.sh /opt/pihole/gravity.sh
$SUDO chmod 755 /usr/local/bin/{gravity,chronometer,whitelist,blacklist,piholeLogFlush,updateDashboard}.sh $SUDO cp /etc/.pihole/advanced/Scripts/chronometer.sh /opt/pihole/chronometer.sh
$SUDO cp /etc/.pihole/advanced/Scripts/whitelist.sh /opt/pihole/whitelist.sh
$SUDO cp /etc/.pihole/advanced/Scripts/blacklist.sh /opt/pihole/blacklist.sh
$SUDO cp /etc/.pihole/advanced/Scripts/piholeDebug.sh /opt/pihole/piholeDebug.sh
$SUDO cp /etc/.pihole/advanced/Scripts/piholeLogFlush.sh /opt/pihole/piholeLogFlush.sh
$SUDO cp /etc/.pihole/advanced/Scripts/updateDashboard.sh /opt/pihole/updateDashboard.sh
$SUDO cp /etc/.pihole/automated\ install/uninstall.sh /opt/pihole/uninstall.sh
$SUDO cp /etc/.pihole/advanced/Scripts/setupLCD.sh /opt/pihole/setupLCD.sh
$SUDO cp /etc/.pihole/advanced/Scripts/version.sh /opt/pihole/version.sh
$SUDO chmod 755 /opt/pihole/{gravity,chronometer,whitelist,blacklist,piholeLogFlush,updateDashboard,uninstall,setupLCD,version}.sh
$SUDO cp /etc/.pihole/pihole /usr/local/bin/pihole
$SUDO chmod 755 /usr/local/bin/pihole
$SUDO cp /etc/.pihole/advanced/bash-completion/pihole /etc/bash_completion.d/pihole
. /etc/bash_completion.d/pihole
#Tidy up /usr/local/bin directory if installing over previous install.
oldFiles=( gravity chronometer whitelist blacklist piholeLogFlush updateDashboard uninstall setupLCD piholeDebug)
for i in "${oldFiles[@]}"; do
if [ -f "/usr/local/bin/$i.sh" ]; then
$SUDO rm /usr/local/bin/"$i".sh
fi
done
$SUDO echo " done." $SUDO echo " done."
} }
installConfigs() { installConfigs() {
# Install the configs from /etc/.pihole to their various locations # Install the configs from /etc/.pihole to their various locations
$SUDO echo ":::" $SUDO echo ":::"
$SUDO echo -n "::: Installing configs..." $SUDO echo "::: Installing configs..."
versionCheckDNSmasq versionCheckDNSmasq
$SUDO mv /etc/lighttpd/lighttpd.conf /etc/lighttpd/lighttpd.conf.orig if [ ! -d "/etc/lighttpd" ]; then
$SUDO cp /etc/.pihole/advanced/lighttpd.conf /etc/lighttpd/lighttpd.conf $SUDO mkdir /etc/lighttpd
$SUDO echo " done." $SUDO chown "$USER":root /etc/lighttpd
$SUDO mv /etc/lighttpd/lighttpd.conf /etc/lighttpd/lighttpd.conf.orig
fi
$SUDO cp /etc/.pihole/advanced/$LIGHTTPD_CFG /etc/lighttpd/lighttpd.conf
$SUDO mkdir -p /var/run/lighttpd
$SUDO chown $LIGHTTPD_USER:$LIGHTTPD_GROUP /var/run/lighttpd
$SUDO mkdir -p /var/cache/lighttpd/compress
$SUDO chown $LIGHTTPD_USER:$LIGHTTPD_GROUP /var/cache/lighttpd/compress
} }
stopServices() { stopServices() {
# Stop dnsmasq and lighttpd # Stop dnsmasq and lighttpd
$SUDO echo ":::" $SUDO echo ":::"
$SUDO echo -n "::: Stopping services..." $SUDO echo -n "::: Stopping services..."
$SUDO service dnsmasq stop & spinner $! || true #$SUDO service dnsmasq stop & spinner $! || true
$SUDO service lighttpd stop & spinner $! || true if [ -x "$(command -v systemctl)" ]; then
$SUDO systemctl stop lighttpd & spinner $! || true
else
$SUDO service lighttpd stop & spinner $! || true
fi
$SUDO echo " done." $SUDO echo " done."
} }
checkForDependencies() { installerDependencies() {
#Running apt-get update/upgrade with minimal output can cause some issues with #Running apt-get update/upgrade with minimal output can cause some issues with
#requiring user input (e.g password for phpmyadmin see #218) #requiring user input (e.g password for phpmyadmin see #218)
#We'll change the logic up here, to check to see if there are any updates availible and #We'll change the logic up here, to check to see if there are any updates availible and
# if so, advise the user to run apt-get update/upgrade at their own discretion # if so, advise the user to run apt-get update/upgrade at their own discretion
#Check to see if apt-get update has already been run today #Check to see if apt-get update has already been run today
# it needs to have been run at least once on new installs! # it needs to have been run at least once on new installs!
timestamp=$(stat -c %Y $PKG_CACHE)
timestamp=$(stat -c %Y /var/cache/apt/) timestampAsDate=$(date -d @"$timestamp" "+%b %e")
timestampAsDate=$(date -d @$timestamp "+%b %e")
today=$(date "+%b %e") today=$(date "+%b %e")
if [ ! "$today" == "$timestampAsDate" ]; then if [ ! "$today" == "$timestampAsDate" ]; then
#update package lists #update package lists
echo ":::"
echo -n "::: apt-get update has not been run today. Running now..."
$SUDO apt-get -qq update & spinner $!
echo " done!"
fi
echo ":::" echo ":::"
echo -n "::: Checking apt-get for upgraded packages...." echo -n "::: $PKG_MANAGER update has not been run today. Running now..."
updatesToInstall=$(sudo apt-get -s -o Debug::NoLocking=true upgrade | grep -c ^Inst) $SUDO $UPDATE_PKG_CACHE > /dev/null 2>&1
echo " done!" echo " done!"
fi
echo ":::"
echo -n "::: Checking $PKG_MANAGER for upgraded packages...."
updatesToInstall=$(eval "$SUDO $PKG_COUNT")
echo " done!"
echo ":::"
if [[ $updatesToInstall -eq "0" ]]; then
echo "::: Your pi is up to date! Continuing with pi-hole installation..."
else
echo "::: There are $updatesToInstall updates availible for your pi!"
echo "::: We recommend you run '$PKG_UPDATE' after installing Pi-Hole! "
echo ":::" echo ":::"
if [[ $updatesToInstall -eq "0" ]]; then fi
echo "::: Your pi is up to date! Continuing with pi-hole installation..." echo ":::"
else echo "::: Checking installer dependencies..."
echo "::: There are $updatesToInstall updates availible for your pi!" for i in "${INSTALLER_DEPS[@]}"; do
echo "::: We recommend you run 'sudo apt-get upgrade' after installing Pi-Hole! "
echo ":::"
fi
echo ":::"
echo "::: Checking dependencies:"
dependencies=( dnsutils bc toilet figlet dnsmasq lighttpd php5-common php5-cgi php5 git curl unzip wget )
for i in "${dependencies[@]}"
do
:
echo -n "::: Checking for $i..." echo -n "::: Checking for $i..."
if [ $(dpkg-query -W -f='${Status}' $i 2>/dev/null | grep -c "ok installed") -eq 0 ]; then package_check $i > /dev/null
if ! [ $? -eq 0 ]; then
echo -n " Not found! Installing...." echo -n " Not found! Installing...."
$SUDO apt-get -y -qq install $i > /dev/null & spinner $! $SUDO $PKG_INSTALL "$i" > /dev/null 2>&1
echo " done!" echo " done!"
else else
echo " already installed!" echo " already installed!"
@ -417,6 +640,23 @@ checkForDependencies() {
done done
} }
checkForDependencies() {
# Install dependencies for Pi-Hole
echo "::: Checking Pi-Hole dependencies:"
for i in "${PIHOLE_DEPS[@]}"; do
echo -n "::: Checking for $i..."
package_check $i > /dev/null
if ! [ $? -eq 0 ]; then
echo -n " Not found! Installing...."
$SUDO $PKG_INSTALL "$i" > /dev/null & spinner $!
echo " done!"
else
echo " already installed!"
fi
done
}
getGitFiles() { getGitFiles() {
# Setup git repos for base files and web admin # Setup git repos for base files and web admin
echo ":::" echo ":::"
@ -439,18 +679,18 @@ getGitFiles() {
is_repo() { is_repo() {
# If the directory does not have a .git folder it is not a repo # If the directory does not have a .git folder it is not a repo
echo -n "::: Checking $1 is a repo..." echo -n "::: Checking $1 is a repo..."
if [ -d "$1/.git" ]; then if [ -d "$1/.git" ]; then
echo " OK!" echo " OK!"
return 1 return 1
fi fi
echo " not found!!" echo " not found!!"
return 0 return 0
} }
make_repo() { make_repo() {
# Remove the non-repod interface and clone the interface # Remove the non-repod interface and clone the interface
echo -n "::: Cloning $2 into $1..." echo -n "::: Cloning $2 into $1..."
$SUDO rm -rf $1 $SUDO rm -rf "$1"
$SUDO git clone -q "$2" "$1" > /dev/null & spinner $! $SUDO git clone -q "$2" "$1" > /dev/null & spinner $!
echo " done!" echo " done!"
} }
@ -458,7 +698,7 @@ make_repo() {
update_repo() { update_repo() {
# Pull the latest commits # Pull the latest commits
echo -n "::: Updating repo in $1..." echo -n "::: Updating repo in $1..."
cd "$1" cd "$1" || exit
$SUDO git pull -q > /dev/null & spinner $! $SUDO git pull -q > /dev/null & spinner $!
echo " done!" echo " done!"
} }
@ -486,10 +726,20 @@ installPiholeWeb() {
$SUDO echo " Existing page detected, not overwriting" $SUDO echo " Existing page detected, not overwriting"
else else
$SUDO mkdir /var/www/html/pihole $SUDO mkdir /var/www/html/pihole
$SUDO mv /var/www/html/index.lighttpd.html /var/www/html/index.lighttpd.orig if [ -f /var/www/html/index.lighttpd.html ]; then
$SUDO cp /etc/.pihole/advanced/index.html /var/www/html/pihole/index.html $SUDO mv /var/www/html/index.lighttpd.html /var/www/html/index.lighttpd.orig
else
printf "\n:::\tNo default index.lighttpd.html file found... not backing up"
fi
$SUDO cp /etc/.pihole/advanced/index.* /var/www/html/pihole/.
$SUDO echo " done!" $SUDO echo " done!"
fi fi
# Install Sudoer file
echo -n "::: Installing sudoer file..."
$SUDO mkdir -p /etc/sudoers.d/
$SUDO cp /etc/.pihole/advanced/pihole.sudo /etc/sudoers.d/pihole
$SUDO chmod 0440 /etc/sudoers.d/pihole
echo " done!"
} }
installCron() { installCron() {
@ -503,58 +753,136 @@ installCron() {
runGravity() { runGravity() {
# Rub gravity.sh to build blacklists # Rub gravity.sh to build blacklists
$SUDO echo ":::" $SUDO echo ":::"
$SUDO echo "::: Preparing to run gravity.sh to refresh hosts..." $SUDO echo "::: Preparing to run gravity.sh to refresh hosts..."
if ls /etc/pihole/list* 1> /dev/null 2>&1; then if ls /etc/pihole/list* 1> /dev/null 2>&1; then
echo "::: Cleaning up previous install (preserving whitelist/blacklist)" echo "::: Cleaning up previous install (preserving whitelist/blacklist)"
$SUDO rm /etc/pihole/list.* $SUDO rm /etc/pihole/list.*
fi fi
#Don't run as SUDO, this was causing issues
echo "::: Running gravity.sh" echo "::: Running gravity.sh"
echo ":::" $SUDO /opt/pihole/gravity.sh
/usr/local/bin/gravity.sh
} }
setUser(){
# Check if user pihole exists and create if not
echo "::: Checking if user 'pihole' exists..."
if id -u pihole > /dev/null 2>&1; then
echo "::: User 'pihole' already exists"
else
echo "::: User 'pihole' doesn't exist. Creating..."
$SUDO useradd -r -s /usr/sbin/nologin pihole
fi
}
configureFirewall() {
# Allow HTTP and DNS traffic
if [ -x "$(command -v firewall-cmd)" ]; then
$SUDO firewall-cmd --state > /dev/null
if [[ $? -eq 0 ]]; then
$SUDO echo "::: Configuring firewalld for httpd and dnsmasq.."
$SUDO firewall-cmd --permanent --add-port=80/tcp
$SUDO firewall-cmd --permanent --add-port=53/tcp
$SUDO firewall-cmd --permanent --add-port=53/udp
$SUDO firewall-cmd --reload
fi
elif [ -x "$(command -v iptables)" ]; then
$SUDO echo "::: Configuring iptables for httpd and dnsmasq.."
$SUDO iptables -A INPUT -p tcp -m tcp --dport 80 -j ACCEPT
$SUDO iptables -A INPUT -p tcp -m tcp --dport 53 -j ACCEPT
$SUDO iptables -A INPUT -p udp -m udp --dport 53 -j ACCEPT
else
$SUDO echo "::: No firewall detected.. skipping firewall configuration."
fi
}
installPihole() { installPihole() {
# Install base files and web interface # Install base files and web interface
checkForDependencies # done checkForDependencies # done
stopServices stopServices
setUser
$SUDO mkdir -p /etc/pihole/ $SUDO mkdir -p /etc/pihole/
$SUDO chown www-data:www-data /var/www/html if [ ! -d "/var/www/html" ]; then
$SUDO mkdir -p /var/www/html
fi
$SUDO chown $LIGHTTPD_USER:$LIGHTTPD_GROUP /var/www/html
$SUDO chmod 775 /var/www/html $SUDO chmod 775 /var/www/html
$SUDO usermod -a -G www-data pi $SUDO usermod -a -G $LIGHTTPD_GROUP pihole
$SUDO lighty-enable-mod fastcgi fastcgi-php > /dev/null if [ -x "$(command -v lighty-enable-mod)" ]; then
$SUDO lighty-enable-mod fastcgi fastcgi-php > /dev/null
else
printf "\n:::\tWarning: 'lighty-enable-mod' utility not found. Please ensure fastcgi is enabled if you experience issues.\n"
fi
getGitFiles getGitFiles
installScripts installScripts
installConfigs installConfigs
#installWebAdmin
CreateLogFile CreateLogFile
configureSelinux
installPiholeWeb installPiholeWeb
installCron installCron
runGravity runGravity
configureFirewall
}
configureSelinux() {
if [ -x "$(command -v getenforce)" ]; then
printf "\n::: SELinux Detected\n"
printf ":::\tChecking for SELinux policy development packages..."
package_check "selinux-policy-devel" > /dev/null
if ! [ $? -eq 0 ]; then
echo -n " Not found! Installing...."
$SUDO $PKG_INSTALL "selinux-policy-devel" > /dev/null & spinner $!
echo " done!"
else
echo " already installed!"
fi
printf "::: Enabling httpd server side includes (SSI).. "
$SUDO setsebool -P httpd_ssi_exec on
if [ $? -eq 0 ]; then
echo -n "Success\n"
fi
printf ":::\tCompiling Pi-Hole SELinux policy..\n"
$SUDO checkmodule -M -m -o /etc/pihole/pihole.mod /etc/.pihole/advanced/selinux/pihole.te
$SUDO semodule_package -o /etc/pihole/pihole.pp -m /etc/pihole/pihole.mod
$SUDO semodule -i /etc/pihole/pihole.pp
$SUDO rm -f /etc/pihole/pihole.mod
$SUDO semodule -l | grep pihole > /dev/null
if [ $? -eq 0 ]; then
printf "::: Successfully installed Pi-Hole SELinux policy\n"
else
printf "::: Warning: Pi-Hole SELinux policy did not install correctly!\n"
fi
fi
} }
displayFinalMessage() { displayFinalMessage() {
# Final completion message to user # Final completion message to user
whiptail --msgbox --backtitle "Make it so." --title "Installation Complete!" "Configure your devices to use the Pi-hole as their DNS server using: whiptail --msgbox --backtitle "Make it so." --title "Installation Complete!" "Configure your devices to use the Pi-hole as their DNS server using:
$IPv4addr IPv4: ${IPv4addr%/*}
$piholeIPv6 IPv6: $piholeIPv6
If you set a new IP address, you should restart the Pi. If you set a new IP address, you should restart the Pi.
The install log is in /etc/pihole." $r $c The install log is in /etc/pihole.
View the web interface at http://pi.hole/admin or http://${IPv4addr%/*}/admin" $r $c
} }
######## SCRIPT ############ ######## SCRIPT ############
# Start the installer # Start the installer
$SUDO mkdir -p /etc/pihole/ $SUDO mkdir -p /etc/pihole/
# Install packages used by this installation script
installerDependencies
welcomeDialogs welcomeDialogs
# Verify there is enough disk space for the install
verifyFreeDiskSpace
# Just back up the original Pi-hole right away since it won't take long and it gets it out of the way # Just back up the original Pi-hole right away since it won't take long and it gets it out of the way
backupLegacyPihole backupLegacyPihole
# Find IP used to route to outside world
findIPRoute
# Find interfaces and let the user choose one # Find interfaces and let the user choose one
chooseInterface chooseInterface
# Let the user decide if they want to block ads over IPv4 and/or IPv6 # Let the user decide if they want to block ads over IPv4 and/or IPv6
@ -571,6 +899,26 @@ $SUDO mv $tmpLog $instalLogLoc
displayFinalMessage displayFinalMessage
echo -n "::: Restarting services..."
# Start services # Start services
$SUDO service dnsmasq start if [ -x "$(command -v systemctl)" ]; then
$SUDO service lighttpd start $SUDO systemctl enable dnsmasq
$SUDO systemctl restart dnsmasq
$SUDO systemctl enable lighttpd
$SUDO systemctl start lighttpd
else
$SUDO service dnsmasq restart
$SUDO service lighttpd start
fi
echo " done."
echo ":::"
echo "::: Installation Complete! Configure your devices to use the Pi-hole as their DNS server using:"
echo "::: ${IPv4addr%/*}"
echo "::: $piholeIPv6"
echo ":::"
echo "::: If you set a new IP address, you should restart the Pi."
echo ":::"
echo "::: The install log is located at: /etc/pihole/install.log"
echo "::: View the web interface at http://pi.hole/admin or http://${IPv4addr%/*}/admin"

199
automated install/uninstall.sh Normal file → Executable file
View file

@ -12,62 +12,165 @@
# Must be root to uninstall # Must be root to uninstall
if [[ $EUID -eq 0 ]];then if [[ $EUID -eq 0 ]];then
echo "You are root." echo "::: You are root."
else else
echo "sudo will be used for the install." echo "::: Sudo will be used for the uninstall."
# Check if it is actually installed # Check if it is actually installed
# If it isn't, exit because the unnstall cannot complete # If it isn't, exit because the unnstall cannot complete
if [[ $(dpkg-query -s sudo) ]];then if [ -x "$(command -v sudo)" ];then
export SUDO="sudo" export SUDO="sudo"
else else
echo "Please install sudo or run this as root." echo "::: Please install sudo or run this as root."
exit 1 exit 1
fi fi
fi fi
# Compatability
if [ -x "$(command -v rpm)" ];then
# Fedora Family
if [ -x "$(command -v dnf)" ];then
PKG_MANAGER="dnf"
else
PKG_MANAGER="yum"
fi
PKG_REMOVE="$PKG_MANAGER remove -y"
PIHOLE_DEPS=( bind-utils bc dnsmasq lighttpd lighttpd-fastcgi php-common git curl unzip wget findutils )
package_check() {
rpm -qa | grep ^$1- > /dev/null
}
package_cleanup() {
$SUDO $PKG_MANAGER -y autoremove
}
elif [ -x "$(command -v apt-get)" ];then
# Debian Family
PKG_MANAGER="apt-get"
PKG_REMOVE="$PKG_MANAGER -y remove --purge"
PIHOLE_DEPS=( dnsutils bc dnsmasq lighttpd php5-common git curl unzip wget )
package_check() {
dpkg-query -W -f='${Status}' "$1" 2>/dev/null | grep -c "ok installed"
}
package_cleanup() {
$SUDO $PKG_MANAGER -y autoremove
$SUDO $PKG_MANAGER -y autoclean
}
else
echo "OS distribution not supported"
exit
fi
spinner()
{
local pid=$1
local delay=0.50
local spinstr='/-\|'
while [ "$(ps a | awk '{print $1}' | grep "$pid")" ]; do
local temp=${spinstr#?}
printf " [%c] " "$spinstr"
local spinstr=$temp${spinstr%"$temp"}
sleep $delay
printf "\b\b\b\b\b\b"
done
printf " \b\b\b\b"
}
function removeAndPurge {
# Purge dependencies
echo ":::"
for i in "${PIHOLE_DEPS[@]}"; do
package_check $i > /dev/null
if [ $? -eq 0 ]; then
while true; do
read -rp "::: Do you wish to remove $i from your system? [y/n]: " yn
case $yn in
[Yy]* ) printf ":::\tRemoving %s..." "$i"; $SUDO $PKG_REMOVE "$i" &> /dev/null & spinner $!; printf "done!\n"; break;;
[Nn]* ) printf ":::\tSkipping %s" "$i\n"; break;;
* ) printf "::: You must answer yes or no!\n";;
esac
done
else
printf ":::\tPackage %s not installed... Not removing.\n" "$i"
fi
done
# Remove dependency config files
echo "::: Removing dnsmasq config files..."
$SUDO rm /etc/dnsmasq.conf /etc/dnsmasq.conf.orig /etc/dnsmasq.d/01-pihole.conf &> /dev/null
# Take care of any additional package cleaning
printf "::: Auto removing & cleaning remaining dependencies..."
package_cleanup &> /dev/null & spinner $!; printf "done!\n";
# Call removeNoPurge to remove PiHole specific files
removeNoPurge
}
function removeNoPurge {
echo ":::"
# Only web directories/files that are created by pihole should be removed.
echo "::: Removing the Pi-hole Web server files..."
$SUDO rm -rf /var/www/html/admin &> /dev/null
$SUDO rm -rf /var/www/html/pihole &> /dev/null
$SUDO rm /var/www/html/index.lighttpd.orig &> /dev/null
# If the web directory is empty after removing these files, then the parent html folder can be removed.
if [ -d "/var/www/html" ]; then
if [[ ! "$(ls -A /var/www/html)" ]]; then
$SUDO rm -rf /var/www/html &> /dev/null
fi
fi
# Attempt to preserve backwards compatibility with older versions
# to guarantee no additional changes were made to /etc/crontab after
# the installation of pihole, /etc/crontab.pihole should be permanently
# preserved.
if [[ -f /etc/crontab.orig ]]; then
echo "::: Initial Pi-hole cron detected. Restoring the default system cron..."
$SUDO mv /etc/crontab /etc/crontab.pihole
$SUDO mv /etc/crontab.orig /etc/crontab
$SUDO service cron restart
fi
# Attempt to preserve backwards compatibility with older versions
if [[ -f /etc/cron.d/pihole ]];then
echo "::: Removing cron.d/pihole..."
$SUDO rm /etc/cron.d/pihole &> /dev/null
fi
echo "::: Removing config files and scripts..."
package_check $i > /dev/null
if [ $? -eq 1 ]; then
$SUDO rm -rf /etc/lighttpd/ &> /dev/null
else
if [ -f /etc/lighttpd/lighttpd.conf.orig ]; then
$SUDO mv /etc/lighttpd/lighttpd.conf.orig /etc/lighttpd/lighttpd.conf
fi
fi
$SUDO rm /etc/dnsmasq.d/adList.conf &> /dev/null
$SUDO rm /etc/dnsmasq.d/01-pihole.conf &> /dev/null
$SUDO rm -rf /var/log/*pihole* &> /dev/null
$SUDO rm -rf /etc/pihole/ &> /dev/null
$SUDO rm -rf /etc/.pihole/ &> /dev/null
$SUDO rm -rf /opt/pihole/ &> /dev/null
$SUDO rm /usr/local/bin/pihole &> /dev/null
$SUDO rm /etc/bash_completion.d/pihole &> /dev/null
$SUDO rm /etc/sudoers.d/pihole &> /dev/null
echo ":::"
printf "::: Finished removing PiHole from your system. Sorry to see you go!\n"
printf "::: Reach out to us at https://github.com/pi-hole/pi-hole/issues if you need help\n"
printf "::: Reinstall by simpling running\n:::\n:::\tcurl -L https://install.pi-hole.net | bash\n:::\n::: at any time!\n:::\n"
printf "::: PLEASE RESET YOUR DNS ON YOUR ROUTER/CLIENTS TO RESTORE INTERNET CONNECTIVITY!\n"
}
######### SCRIPT ########### ######### SCRIPT ###########
$SUDO apt-get -y remove --purge dnsutils bc toilet echo "::: Preparing to remove packages, be sure that each may be safely removed depending on your operating system."
$SUDO apt-get -y remove --purge dnsmasq echo "::: (SAFE TO REMOVE ALL ON RASPBIAN)"
$SUDO apt-get -y remove --purge lighttpd php5-common php5-cgi php5 while true; do
read -rp "::: Do you wish to purge PiHole's dependencies from your OS? (You will be prompted for each package) [y/n]: " yn
# Only web directories/files that are created by pihole should be removed. case $yn in
echo "Removing the Pi-hole Web server files..." [Yy]* ) removeAndPurge; break;;
$SUDO rm -rf /var/www/html/admin
$SUDO rm -rf /var/www/html/pihole [Nn]* ) removeNoPurge; break;;
$SUDO rm /var/www/html/index.lighttpd.orig esac
done
# If the web directory is empty after removing these files, then the parent html folder can be removed.
if [[ ! "$(ls -A /var/www/html)" ]]; then
$SUDO rm -rf /var/www/html
fi
echo "Removing dnsmasq config files..."
$SUDO rm /etc/dnsmasq.conf /etc/dnsmasq.conf.orig
# Attempt to preserve backwards compatibility with older versions
# to guarantee no additional changes were made to /etc/crontab after
# the installation of pihole, /etc/crontab.pihole should be permanently
# preserved.
if [[ -f /etc/crontab.orig ]]; then
echo "Initial Pi-hole cron detected. Restoring the default system cron..."
$SUDO mv /etc/crontab /etc/crontab.pihole
$SUDO mv /etc/crontab.orig /etc/crontab
$SUDO service cron restart
fi
# Attempt to preserve backwards compatibility with older versions
if [[ -f /etc/cron.d/pihole ]];then
echo "Removing cron.d/pihole..."
$SUDO rm /etc/cron.d/pihole
fi
echo "Removing config files and scripts..."
$SUDO rm /etc/dnsmasq.conf
$SUDO rm -rf /etc/lighttpd/
$SUDO rm /var/log/pihole.log
$SUDO rm /usr/local/bin/gravity.sh
$SUDO rm /usr/local/bin/chronometer.sh
$SUDO rm /usr/local/bin/whitelist.sh
$SUDO rm /usr/local/bin/piholeLogFlush.sh
$SUDO rm -rf /etc/pihole/

View file

@ -38,6 +38,6 @@ include_shell "/usr/share/lighttpd/use-ipv6.pl " + server.port
include_shell "/usr/share/lighttpd/create-mime.assign.pl" include_shell "/usr/share/lighttpd/create-mime.assign.pl"
include_shell "/usr/share/lighttpd/include-conf-enabled.pl" include_shell "/usr/share/lighttpd/include-conf-enabled.pl"
$HTTP["host"] =~ "ads.hulu.com|ads-v-darwin.hulu.com" { $HTTP["host"] =~ "ads.hulu.com|ads-v-darwin.hulu.com|ads-e-darwin.hulu.com" {
url.redirect = ( ".*" => "http://192.168.1.101:8200/MediaItems/19.mov") url.redirect = ( ".*" => "http://192.168.1.101:8200/MediaItems/19.mov")
} }

View file

@ -12,34 +12,37 @@
# Run this script as root or under sudo # Run this script as root or under sudo
echo ":::" echo ":::"
if [[ $EUID -eq 0 ]];then if [[ $EUID -eq 0 ]];then
echo "::: You are root." echo "::: You are root."
else else
echo "::: sudo will be used." echo "::: sudo will be used."
# Check if it is actually installed # Check if it is actually installed
# If it isn't, exit because the install cannot complete # If it isn't, exit because the install cannot complete
if [[ $(dpkg-query -s sudo) ]];then if [ -x "$(command -v sudo)" ];then
export SUDO="sudo" export SUDO="sudo"
else else
echo "::: Please install sudo or run this script as root." echo "::: Please install sudo or run this script as root."
exit 1 exit 1
fi fi
fi fi
piholeIPfile=/tmp/piholeIP piholeIPfile=/etc/pihole/piholeIP
piholeIPv6file=/etc/pihole/.useIPv6 piholeIPv6file=/etc/pihole/.useIPv6
adListFile=/etc/pihole/adlists.list adListFile=/etc/pihole/adlists.list
adListDefault=/etc/pihole/adlists.default adListDefault=/etc/pihole/adlists.default
whitelistScript=/opt/pihole/whitelist.sh
blacklistScript=/opt/pihole/blacklist.sh
if [[ -f $piholeIPfile ]];then if [[ -f $piholeIPfile ]];then
# If the file exists, it means it was exported from the installation script and we should use that value instead of detecting it in this script # If the file exists, it means it was exported from the installation script and we should use that value instead of detecting it in this script
piholeIP=$(cat $piholeIPfile) piholeIP=$(cat $piholeIPfile)
rm $piholeIPfile #rm $piholeIPfile
else else
# Otherwise, the IP address can be taken directly from the machine, which will happen when the script is run by the user and not the installation script # Otherwise, the IP address can be taken directly from the machine, which will happen when the script is run by the user and not the installation script
IPv4dev=$(ip route get 8.8.8.8 | awk '{for(i=1;i<=NF;i++)if($i~/dev/)print $(i+1)}') IPv4dev=$(ip route get 8.8.8.8 | awk '{for(i=1;i<=NF;i++)if($i~/dev/)print $(i+1)}')
piholeIPCIDR=$(ip -o -f inet addr show dev $IPv4dev | awk '{print $4}' | awk 'END {print}') piholeIPCIDR=$(ip -o -f inet addr show dev "$IPv4dev" | awk '{print $4}' | awk 'END {print}')
piholeIP=${piholeIPCIDR%/*} piholeIP=${piholeIPCIDR%/*}
fi fi
@ -48,22 +51,20 @@ if [[ -f $piholeIPv6file ]];then
piholeIPv6=$(ip -6 route get 2001:4860:4860::8888 | awk -F " " '{ for(i=1;i<=NF;i++) if ($i == "src") print $(i+1) }') piholeIPv6=$(ip -6 route get 2001:4860:4860::8888 | awk -F " " '{ for(i=1;i<=NF;i++) if ($i == "src") print $(i+1) }')
fi fi
# Variables for various stages of downloading and formatting the list # Variables for various stages of downloading and formatting the list
## Nate 3/26/2016 - Commented unused variables
basename=pihole basename=pihole
piholeDir=/etc/$basename piholeDir=/etc/$basename
adList=$piholeDir/gravity.list adList=$piholeDir/gravity.list
blacklist=$piholeDir/blacklist.txt #blacklist=$piholeDir/blacklist.txt
whitelist=$piholeDir/whitelist.txt #whitelist=$piholeDir/whitelist.txt
latentWhitelist=$piholeDir/latentWhitelist.txt #latentWhitelist=$piholeDir/latentWhitelist.txt
justDomainsExtension=domains justDomainsExtension=domains
matterandlight=$basename.0.matterandlight.txt matterandlight=$basename.0.matterandlight.txt
supernova=$basename.1.supernova.txt supernova=$basename.1.supernova.txt
eventHorizon=$basename.2.eventHorizon.txt eventHorizon=$basename.2.eventHorizon.txt
accretionDisc=$basename.3.accretionDisc.txt accretionDisc=$basename.3.accretionDisc.txt
eyeOfTheNeedle=$basename.4.wormhole.txt #eyeOfTheNeedle=$basename.4.wormhole.txt
# After setting defaults, check if there's local overrides # After setting defaults, check if there's local overrides
if [[ -r $piholeDir/pihole.conf ]];then if [[ -r $piholeDir/pihole.conf ]];then
@ -71,22 +72,6 @@ if [[ -r $piholeDir/pihole.conf ]];then
. $piholeDir/pihole.conf . $piholeDir/pihole.conf
fi fi
spinner(){
local pid=$1
local delay=0.001
local spinstr='/-\|'
spin='-\|/'
i=0
while $SUDO kill -0 $pid 2>/dev/null
do
i=$(( (i+1) %4 ))
printf "\b${spin:$i:1}"
sleep .1
done
printf "\b"
}
########################### ###########################
# collapse - begin formation of pihole # collapse - begin formation of pihole
function gravity_collapse() { function gravity_collapse() {
@ -97,19 +82,29 @@ function gravity_collapse() {
#custom file found, use this instead of default #custom file found, use this instead of default
echo -n "::: Custom adList file detected. Reading..." echo -n "::: Custom adList file detected. Reading..."
sources=() sources=()
while read -a line; do while read -r line; do
sources+=($line) #Do not read commented out or blank lines
if [[ $line = \#* ]] || [[ ! $line ]]; then
echo "" > /dev/null
else
sources+=($line)
fi
done < $adListFile done < $adListFile
echo " done!" echo " done!"
else else
#no custom file found, use defaults! #no custom file found, use defaults!
echo -n "::: No custom adlist file detected, reading from default file..." echo -n "::: No custom adlist file detected, reading from default file..."
sources=() sources=()
while read -a line; do while read -r line; do
sources+=($line) #Do not read commented out or blank lines
if [[ $line = \#* ]] || [[ ! $line ]]; then
echo "" > /dev/null
else
sources+=($line)
fi
done < $adListDefault done < $adListDefault
echo " done!" echo " done!"
fi fi
# Create the pihole resource directory if it doesn't exist. Future files will be stored here # Create the pihole resource directory if it doesn't exist. Future files will be stored here
if [[ -d $piholeDir ]];then if [[ -d $piholeDir ]];then
@ -117,12 +112,12 @@ function gravity_collapse() {
# Will update later, needed for existing installs, new installs should # Will update later, needed for existing installs, new installs should
# create this directory as non-root # create this directory as non-root
$SUDO chmod 777 $piholeDir $SUDO chmod 777 $piholeDir
find "$piholeDir" -type f -exec $SUDO chmod 666 {} \; & spinner $! echo ":::"
echo "." echo "::: Existing pihole directory found"
else else
echo -n "::: Creating pihole directory..." echo "::: Creating pihole directory..."
mkdir $piholeDir & spinner $! mkdir $piholeDir
echo " done!" $SUDO chmod 777 $piholeDir
fi fi
} }
@ -134,7 +129,7 @@ function gravity_patternCheck() {
# Some of the blocklists are copyright, they need to be downloaded # Some of the blocklists are copyright, they need to be downloaded
# and stored as is. They can be processed for content after they # and stored as is. They can be processed for content after they
# have been saved. # have been saved.
cp $patternBuffer $saveLocation cp "$patternBuffer" "$saveLocation"
echo " List updated, transport successful!" echo " List updated, transport successful!"
else else
# curl didn't download any host files, probably because of the date check # curl didn't download any host files, probably because of the date check
@ -157,17 +152,16 @@ function gravity_transport() {
fi fi
# Silently curl url # Silently curl url
curl -s $cmd_ext $heisenbergCompensator -A "$agent" $url > $patternBuffer curl -s -L $cmd_ext $heisenbergCompensator -A "$agent" $url > $patternBuffer
# Check for list updates # Check for list updates
gravity_patternCheck $patternBuffer gravity_patternCheck "$patternBuffer"
# Cleanup # Cleanup
rm -f $patternBuffer rm -f "$patternBuffer"
} }
# spinup - main gravity function # spinup - main gravity function
function gravity_spinup() { function gravity_spinup() {
echo "::: " echo ":::"
# Loop through domain list. Download each one and remove commented lines (lines beginning with '# 'or '/') and # blank lines # Loop through domain list. Download each one and remove commented lines (lines beginning with '# 'or '/') and # blank lines
for ((i = 0; i < "${#sources[@]}"; i++)) for ((i = 0; i < "${#sources[@]}"; i++))
do do
@ -186,99 +180,91 @@ function gravity_spinup() {
# Use a case statement to download lists that need special cURL commands # Use a case statement to download lists that need special cURL commands
# to complete properly and reset the user agent when required # to complete properly and reset the user agent when required
case "$domain" in case "$domain" in
"adblock.mahakala.is") "adblock.mahakala.is")
agent='Mozilla/5.0 (X11; Linux x86_64; rv:30.0) Gecko/20100101 Firefox/30.0' agent='Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36'
cmd_ext="-e http://forum.xda-developers.com/" cmd_ext="-e http://forum.xda-developers.com/"
;; ;;
"pgl.yoyo.org") "pgl.yoyo.org")
cmd_ext="-d mimetype=plaintext -d hostformat=hosts" cmd_ext="-d mimetype=plaintext -d hostformat=hosts"
;; ;;
# Default is a simple request # Default is a simple request
*) cmd_ext="" *) cmd_ext=""
esac esac
gravity_transport $url $cmd_ext $agent gravity_transport "$url" "$cmd_ext" "$agent"
done done
} }
# Schwarzchild - aggregate domains to one list and add blacklisted domains # Schwarzchild - aggregate domains to one list and add blacklisted domains
function gravity_Schwarzchild() { function gravity_Schwarzchild() {
echo "::: " echo "::: "
# Find all active domains and compile them into one file and remove CRs # Find all active domains and compile them into one file and remove CRs
echo -n "::: Aggregating list of domains..." echo -n "::: Aggregating list of domains..."
truncate -s 0 $piholeDir/$matterandlight & spinner $! truncate -s 0 $piholeDir/$matterandlight
for i in "${activeDomains[@]}" for i in "${activeDomains[@]}"
do do
cat $i |tr -d '\r' >> $piholeDir/$matterandlight cat "$i" | tr -d '\r' >> $piholeDir/$matterandlight
done done
echo " done!" echo " done!"
} }
function gravity_Blacklist(){ function gravity_Blacklist(){
# Append blacklist entries if they exist # Append blacklist entries if they exist
echo -n "::: Running blacklist script to update HOSTS file...." echo -n "::: Running blacklist script to update HOSTS file...."
blacklist.sh -f -nr -q > /dev/null & spinner $! $blacklistScript -f -nr -q > /dev/null
numBlacklisted=$(wc -l < "/etc/pihole/blacklist.txt") numBlacklisted=$(wc -l < "/etc/pihole/blacklist.txt")
plural=; [[ "$numBlacklisted" != "1" ]] && plural=s plural=; [[ "$numBlacklisted" != "1" ]] && plural=s
echo " $numBlacklisted domain${plural} blacklisted!" echo " $numBlacklisted domain${plural} blacklisted!"
} }
function gravity_Whitelist() { function gravity_Whitelist() {
echo ":::" echo ":::"
# Prevent our sources from being pulled into the hole # Prevent our sources from being pulled into the hole
plural=; [[ "${sources[@]}" != "1" ]] && plural=s plural=; [[ "${sources[@]}" != "1" ]] && plural=s
echo -n "::: Adding ${#sources[@]} ad list source${plural} to the whitelist..." echo -n "::: Adding ${#sources[@]} adlist source${plural} to the whitelist..."
urls=() urls=()
for url in ${sources[@]} for url in "${sources[@]}"
do do
tmp=$(echo "$url" | awk -F '/' '{print $3}') tmp=$(echo "$url" | awk -F '/' '{print $3}')
urls=("${urls[@]}" $tmp) urls=("${urls[@]}" $tmp)
done done
echo " done!" echo " done!"
echo -n "::: Running whitelist script to update HOSTS file...." echo -n "::: Running whitelist script to update HOSTS file...."
whitelist.sh -f -nr -q ${urls[@]} > /dev/null & spinner $! $whitelistScript -f -nr -q "${urls[@]}" > /dev/null
numWhitelisted=$(wc -l < "/etc/pihole/whitelist.txt") numWhitelisted=$(wc -l < "/etc/pihole/whitelist.txt")
plural=; [[ "$numWhitelisted" != "1" ]] && plural=s plural=; [[ "$numWhitelisted" != "1" ]] && plural=s
echo " $numWhitelisted domain${plural} whitelisted!" echo " $numWhitelisted domain${plural} whitelisted!"
} }
function gravity_unique() { function gravity_unique() {
# Sort and remove duplicates # Sort and remove duplicates
echo -n "::: Removing duplicate domains...." echo -n "::: Removing duplicate domains...."
sort -u $piholeDir/$supernova > $piholeDir/$eventHorizon & spinner $! sort -u $piholeDir/$supernova > $piholeDir/$eventHorizon
echo " done!" echo " done!"
numberOf=$(wc -l < $piholeDir/$eventHorizon) numberOf=$(wc -l < $piholeDir/$eventHorizon)
echo "::: $numberOf unique domains trapped in the event horizon." echo "::: $numberOf unique domains trapped in the event horizon."
} }
function gravity_hostFormat() { function gravity_hostFormat() {
# Format domain list as "192.168.x.x domain.com" # Format domain list as "192.168.x.x domain.com"
echo "::: Formatting domains into a HOSTS file..." echo "::: Formatting domains into a HOSTS file..."
# If there is a value in the $piholeIPv6, then IPv6 will be used, so the awk command modified to create a line for both protocols hostname=$(</etc/hostname)
if [[ -n $piholeIPv6 ]];then # If there is a value in the $piholeIPv6, then IPv6 will be used, so the awk command modified to create a line for both protocols
#Add dummy domain Pi-Hole.IsWorking.OK to the top of gravity.list to make ping result return a friendlier looking domain! if [[ -n $piholeIPv6 ]];then
echo -e "$piholeIP Pi-Hole.IsWorking.OK \n$piholeIPv6 Pi-Hole.IsWorking.OK" > $piholeDir/$accretionDisc # Add hostname and dummy domain to the top of gravity.list to make ping result return a friendlier looking domain! Also allows for an easy way to access the Pi-hole admin console (pi.hole/admin)
cat $piholeDir/$eventHorizon | awk -v ipv4addr="$piholeIP" -v ipv6addr="$piholeIPv6" '{sub(/\r$/,""); print ipv4addr" "$0"\n"ipv6addr" "$0}' >> $piholeDir/$accretionDisc echo -e "$piholeIP $hostname\n$piholeIPv6 $hostname\n$piholeIP pi.hole\n$piholeIPv6 pi.hole" > $piholeDir/$accretionDisc
cat $piholeDir/$eventHorizon | awk -v ipv4addr="$piholeIP" -v ipv6addr="$piholeIPv6" '{sub(/\r$/,""); print ipv4addr" "$0"\n"ipv6addr" "$0}' >> $piholeDir/$accretionDisc
else else
# Otherwise, just create gravity.list as normal using IPv4 # Otherwise, just create gravity.list as normal using IPv4
#Add dummy domain Pi-Hole.IsWorking.OK to the top of gravity.list to make ping result return a friendlier looking domain! # Add hostname and dummy domain to the top of gravity.list to make ping result return a friendlier looking domain! Also allows for an easy way to access the Pi-hole admin console (pi.hole/admin)
echo -e "$piholeIP Pi-Hole.IsWorking.OK" > $piholeDir/$accretionDisc echo -e "$piholeIP $hostname\n$piholeIP pi.hole" > $piholeDir/$accretionDisc
cat $piholeDir/$eventHorizon | awk -v ipv4addr="$piholeIP" '{sub(/\r$/,""); print ipv4addr" "$0}' >> $piholeDir/$accretionDisc cat $piholeDir/$eventHorizon | awk -v ipv4addr="$piholeIP" '{sub(/\r$/,""); print ipv4addr" "$0}' >> $piholeDir/$accretionDisc
fi fi
# Copy the file over as /etc/pihole/gravity.list so dnsmasq can use it # Copy the file over as /etc/pihole/gravity.list so dnsmasq can use it
cp $piholeDir/$accretionDisc $adList cp $piholeDir/$accretionDisc $adList
} }
@ -289,44 +275,55 @@ function gravity_blackbody() {
for file in $piholeDir/*.$justDomainsExtension for file in $piholeDir/*.$justDomainsExtension
do do
# If list is in active array then leave it (noop) else rm the list # If list is in active array then leave it (noop) else rm the list
if [[ " ${activeDomains[@]} " =~ " ${file} " ]]; then if [[ " ${activeDomains[@]} " =~ ${file} ]]; then
: :
else else
rm -f $file rm -f "$file"
fi fi
done done
} }
function gravity_advanced() { function gravity_advanced() {
# Remove comments and print only the domain name # Remove comments and print only the domain name
# Most of the lists downloaded are already in hosts file format but the spacing/formating is not contigious # Most of the lists downloaded are already in hosts file format but the spacing/formating is not contigious
# This helps with that and makes it easier to read # This helps with that and makes it easier to read
# It also helps with debugging so each stage of the script can be researched more in depth # It also helps with debugging so each stage of the script can be researched more in depth
echo -n "::: Formatting list of domains to remove comments...." echo -n "::: Formatting list of domains to remove comments...."
awk '($1 !~ /^#/) { if (NF>1) {print $2} else {print $1}}' $piholeDir/$matterandlight | sed -nr -e 's/\.{2,}/./g' -e '/\./p' > $piholeDir/$supernova & spinner $! awk '($1 !~ /^#/) { if (NF>1) {print $2} else {print $1}}' $piholeDir/$matterandlight | sed -nr -e 's/\.{2,}/./g' -e '/\./p' > $piholeDir/$supernova
echo " done!" echo " done!"
numberOf=$(wc -l < $piholeDir/$supernova) numberOf=$(wc -l < $piholeDir/$supernova)
echo "::: $numberOf domains being pulled in by gravity..." echo "::: $numberOf domains being pulled in by gravity..."
gravity_unique gravity_unique
} }
function gravity_reload() { function gravity_reload() {
#Clear no longer needed files...
echo ":::"
echo -n "::: Cleaning up un-needed files..."
$SUDO rm $piholeDir/pihole.*.txt
echo " done!"
# Reload hosts file # Reload hosts file
echo ":::" echo ":::"
echo -n "::: Refresh lists in dnsmasq..." echo -n "::: Refresh lists in dnsmasq..."
#ensure /etc/dnsmasq.d/01-pihole.conf is pointing at the correct list!
#First escape forward slashes in the path:
adList=${adList//\//\\\/}
#Now replace the line in dnsmasq file
$SUDO sed -i "s/^addn-hosts.*/addn-hosts=$adList/" /etc/dnsmasq.d/01-pihole.conf
dnsmasqPid=$(pidof dnsmasq) dnsmasqPid=$(pidof dnsmasq)
find "$piholeDir" -type f -exec $SUDO chmod 666 {} \;
if [[ $dnsmasqPid ]]; then if [[ $dnsmasqPid ]]; then
# service already running - reload config # service already running - reload config
$SUDO kill -HUP $dnsmasqPid & spinner $! $SUDO killall -s HUP dnsmasq
else else
# service not running, start it up # service not running, start it up
$SUDO service dnsmasq start & spinner $! $SUDO service dnsmasq start
fi fi
echo " done!" echo " done!"
} }

121
pihole Executable file
View file

@ -0,0 +1,121 @@
#!/bin/bash
# Pi-hole: A black hole for Internet advertisements
# (c) 2015, 2016 by Jacob Salmela
# Network-wide ad blocking via your Raspberry Pi
# http://pi-hole.net
# Controller for all pihole scripts and functions.
#
# Pi-hole is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
# Must be root to use this tool
if [[ ! $EUID -eq 0 ]];then
#echo "::: You are root."
#else
#echo "::: Sudo will be used for this tool."
# Check if it is actually installed
# If it isn't, exit because the pihole cannot be invoked without privileges.
if [ -x "$(command -v sudo)" ];then
export SUDO="sudo"
else
echo "::: Please install sudo or run this as root."
exit 1
fi
fi
function whitelistFunc {
shift
$SUDO /opt/pihole/whitelist.sh "$@"
exit 1
}
function blacklistFunc {
shift
$SUDO /opt/pihole/blacklist.sh "$@"
exit 1
}
function debugFunc {
$SUDO /opt/pihole/piholeDebug.sh
exit 1
}
function flushFunc {
$SUDO /opt/pihole/piholeLogFlush.sh
exit 1
}
function updateDashboardFunc {
$SUDO /opt/pihole/updateDashboard.sh
exit 1
}
function updateGravityFunc {
$SUDO /opt/pihole/gravity.sh
exit 1
}
function setupLCDFunction {
$SUDO /opt/pihole/setupLCD.sh
exit 1
}
function chronometerFunc {
shift
$SUDO /opt/pihole/chronometer.sh "$@"
exit 1
}
function uninstallFunc {
$SUDO /opt/pihole/uninstall.sh
exit 1
}
function versionFunc {
$SUDO /opt/pihole/version.sh
exit 1
}
function helpFunc {
echo "::: Control all PiHole specific functions!"
echo ":::"
echo "::: Usage: pihole [options]"
echo "::: Add -h after -w (whitelist), -b (blacklist), or -c (chronometer) for more information on usage"
echo ":::"
echo "::: Options:"
echo "::: -w, whitelist Whitelist domains"
echo "::: -b, blacklist Blacklist domains"
echo "::: -d, debug Start a debugging session if having trouble"
echo "::: -f, flush Flush the pihole.log file"
echo "::: -u, updateDashboard Update the web dashboard manually"
echo "::: -g, updateGravity Update the list of ad-serving domains"
echo "::: -s, setupLCD Automatically configures the Pi to use the 2.8 LCD screen to display stats on it"
echo "::: -c, chronometer Calculates stats and displays to an LCD"
echo "::: -h, help Show this help dialog"
echo "::: -v, version Show current versions"
echo "::: uninstall Uninstall Pi-Hole from your system :(!"
exit 1
}
if [[ $# = 0 ]]; then
helpFunc
fi
# Handle redirecting to specific functions based on arguments
case "$1" in
"-w" | "whitelist" ) whitelistFunc "$@";;
"-b" | "blacklist" ) blacklistFunc "$@";;
"-d" | "debug" ) debugFunc;;
"-f" | "flush" ) flushFunc;;
"-u" | "updateDashboard" ) updateDashboardFunc;;
"-g" | "updateGravity" ) updateGravityFunc;;
"-s" | "setupLCD" ) setupLCDFunction;;
"-c" | "chronometer" ) chronometerFunc "$@";;
"-h" | "help" ) helpFunc;;
"-v" | "version" ) versionFunc;;
"uninstall" ) uninstallFunc;;
* ) helpFunc;;
esac