Netgate Discussion Forum
    • Categories
    • Recent
    • Tags
    • Popular
    • Users
    • Search
    • Register
    • Login

    Mywpad.php GUI script para configurar WPAD en pfSense 2.3.x

    Scheduled Pinned Locked Moved Español
    14 Posts 4 Posters 5.5k Views 1 Watching
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • J Offline
      javcasta
      last edited by

      Hola

      Ya pasé el PhP Cli script – WPADcliSetup.php a su versión GUI (a ejecutar desde la GUI de pfSense)

      mywpad.php: Un script php para ser ejecutado desde la GUI de pfSense 2.3.x ( https://ip/mywpad.php )

      Configura a pfSense como servidor de WPAD sin revertir GUI a HTTP.

      Alojar mywpad.php en la ruta /usr/local/www/ y ejecutar https://ip-pfSense/mywpad.php

      Elige la interfaz, marca o desmarca si quieres backup de nginx.conf y/o proxy.pac, y botón apply (aplicar)

      El script, entre otras cosas, detecta si dhcp está enable en la interfaz y si existe entrada en unbound para el host wpad y hace los cambios que tenga que hacer. Si te interesa el código y lo que hace, bajate el fichero :)

      Condiciones necesarias:

      -Para que WPAD se propague vía dhcp, dhcp server debe estar enable en la interfaz seleccionada
          -Para que WPAD se propague vía DNS, pfSense debe tener activado DNS Resolver (unbound)

      Tras clikar el botón apply nos pregunta si estamos seguros (Aceptar)

      Y aparecerá el test de nginx.conf y el contenido de la entrada para el host wpad en unbound. Habrá que clikar el botón Open Services y reiniciar los servicios dhcpd y unbound para que esté operativo WPAD.

      Salu2

      referencias:
      https://www.javcasta.com/pfsense-2-3-x-mywpad-mywpad-php/
      https://forum.pfsense.org/index.php?topic=112715.msg628966#msg628966

      Download: http://www.javcasta.com/?smd_process_download=1&download_id=31263

      Javier Castañón
      Técnico de comunicaciones, soporte y sistemas.

      Mi web: https://javcasta.com/

      Soporte scripting/pfSense https://javcasta.com/soporte/

      1 Reply Last reply Reply Quote 0
      • J Offline
        javcasta
        last edited by

        Hola.

        Una aclaración: En la última imagen pone que restaria o reiniciar pfSense o ejecutar vía shell /usr/local/etc/rc.d/nginx onestart.
        Esto no hace falta, ya el script lanza una instancia de nginx para WPAD.

        Posteo el código (ya que me lo han pedido y de paso tenerlo en otro sitio a modo de backup :) )

        El código:

        
        /* $Id$ */
        /*
        	mywpad.php
        
        	Copyright (c) 2015-2016 Javier Castañon
          javier@javcasta.com - https://javcasta.com/
        	All rights reserved.
        
        	Redistribution and use in source and binary forms, with or without
        	modification, are permitted provided that the following conditions are met:
        
        	1\. Redistributions of source code must retain the above copyright notice,
        	   this list of conditions and the following disclaimer.
        
        	2\. Redistributions in binary form must reproduce the above copyright
        	   notice, this list of conditions and the following disclaimer in the
        	   documentation and/or other materials provided with the distribution.
        
        	THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
        	INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
        	AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
        	AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
        	OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
        	SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
        	INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
        	CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
        	ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
        	POSSIBILITY OF SUCH DAMAGE.
        */
        /*
        	pfSense_MODULE:	system
        */
        
        ##|+PRIV
        ##|*IDENT=page-status-mywpad
        ##|*NAME=Status: MyWPAD page
        ##|*DESCR=Allow access to the 'Status: MyWPAD' page.
        ##|*MATCH=mywpad.php*
        ##|-PRIV
        
        require("guiconfig.inc");
        require_once("config.inc");
        require_once("globals.inc");
        require_once("pfsense-utils.inc");
        require_once("functions.inc");
        require_once("/usr/local/www/widgets/include/interfaces.inc");
        
        global $config, $g;
        $config = parse_config(true);
        $choose = 1;
        //$onchangeselect = 0;
        $lasips = array();
        $lasinterfaces = array();
        $lasintsys = array();
        $lasmasks = array();
        $ifdescrs = get_configured_interface_with_descr();
        $i = 0;
        foreach ($ifdescrs as $ifdescr => $ifname) {
        $ifinfo = get_interface_info($ifdescr);
        //print_r($ifinfo);
        if ($ifinfo['status'] == "up" || $ifinfo['status'] == "associated") {
          $i++;
           if (strpos($ifname, "LAN") !== false) {
             $choose = $i; //$onchangeselect = $i + 1;
             if (isset($_GET['elchoose'])) { $choose = $_GET['elchoose']; }
             //echo $i . " " . "\033[32m".$ifname." - ".$ifinfo['ipaddr']." \033[0m \n";     
             $lasips[] = $ifinfo['ipaddr'];
             $lasmasks[] = $ifinfo['subnet'];
             $lasinterfaces[] = $ifname;
             $lasintsys[] = array_search ("$ifname", $ifdescrs);
           }
           else { 
             //echo $i ." " . $ifname . ' ' . $ifinfo['ipaddr'] . " \033[0m \n";
             //$onchangeselect = $i + 1;
             $lasips[] = $ifinfo['ipaddr'];
             $lasmasks[] = $ifinfo['subnet'];
             $lasinterfaces[] = $ifname;
             $lasintsys[] = array_search ("$ifname", $ifdescrs);
             }
        	}
        } //end foreach
        
        /*
        if (!is_array($config['mywpad']['config']))
        	$config['mywpad']['config'] = array();
        
        $a_mywpad = &$config['mywpad']['config'];
        */
        
        $a_mywpad = Array();
        
        include("head.inc");
        
        $form = new Form;
        $section = new Form_Section('My WPAD Config. (Item with red color: Not editable)');
        
        if (isset($_GET['elchoose'])) { $choose = $_GET['elchoose']; }
        $execute = false;
        //execute 
        if (isset($_GET['execute'])) { $execute = $_GET['execute']; } else { $execute = false; }
        
        //IF0
        if (!$execute) {
        $section->addInput(new Form_Select(
        	'interface',
        	'Interface',
        	$choose - 1,      // Initial value. If it matches on of the selectors it will be highlighted
        	$lasinterfaces
        ))->setHelp('Usually LAN interface');
        }
        
        $section->addInput(new Form_Input(
        	'ip',
        	'IP',
        	'text',
        	$lasips[$choose - 1]
        ))->setHelp("IP where nginx is listen proxy.pac / wpad.dat /wpad.da queries");
        
        $wpadport = 80;
        $section->addInput(new Form_Input(
        	'port',
        	'Port',
        	'text',
        	$wpadport
        ))->setHelp("Port : Usually port tcp 80");
        
        $backupnginx = true;
        $fecha = date("Y").date("m").date("d").date('Hi');
        $backupngnixconf = $fecha."nginx.conf.origin";
        if ($execute) copy("/usr/local/etc/nginx/nginx.conf", "/usr/local/etc/nginx/$backupngnixconf");
        
        if (!$execute) {
        $section->addInput(new Form_Checkbox(
        	'backupnginx',   // checkbox name (id)
        	'Backup nginx.conf', // checkbox label
        	'Backup nginx.conf: /usr/local/etc/nginx/nginx.conf -> /usr/local/etc/nginx/'."$backupngnixconf", // checkbox text
        	 $backupnginx  //$pconfig['backupnginx'] checkbox initial value
        ));
        }
        
            $world = _($lasips[$choose - 1]);
            $world2 = _($config['system']['domain']);
            $world3 = _($wpadport);
            $worldlog1 = _("'".'$remote_addr - $remote_user [$time_local] "$request" '."'");
            $worldlog2 = _("'".'$status $body_bytes_sent "$http_referer" '."'");
            $worldlog3 = _("'".'"$http_user_agent" "$http_x_forwarded_for"'."'");
        
            $str = <<<eof<br>worker_processes  1;
            events {
            worker_connections  1024;
            }
            http {
            include       mime.types;
            #add extra mime types for wpad.dat & wpad.da
            types {
                  application/x-ns-proxy-autoconfig     dat;
                  application/x-ns-proxy-autoconfig     da;
            }
            default_type  application/octet-stream;
            log_format  main  $worldlog1
                              $worldlog2
                              $worldlog3;
        
            sendfile        on;
            #tcp_nopush     on;
        
            #keepalive_timeout  0;
            keepalive_timeout  65;
        
            server {
                listen      $world:$world3;
                server_name  wpad.$world2;
                access_log  /var/log/ngnix/access.log  main;
                location / {
                    root   /usr/local/www/nginx;
                    index  index.html index.htm;
                }
                error_page  404               /usr/local/www/nginx-dist/50x.html;
        
                # redirect server error pages to the static page /50x.html
                error_page   500 502 503 504  /50x.html;
                #error_page   500 502 503 504  /50x.html;
                location = /50x.html {
                    root   /usr/local/www/nginx-dist;
                }
            }
        }
        EOF;
        
        if (!$execute) {
        $section->addInput(new Form_Textarea(
        	'nginx',
        	'New nginx.conf',
        	$str
        ))->setHelp("The New **/usr/local/etc/nginx/nginx.conf** file.");             
        }
        
        if ($execute) {
          if (!file_exists(dirname("/var/log/ngnix/access.log"))) mkdir(dirname("/var/log/ngnix/access.log"), 0777, true);
          if (!file_exists("/var/log/ngnix/access.log")) file_put_contents("/var/log/ngnix/access.log", "");
          file_put_contents("/usr/local/etc/nginx/nginx.conf", $str);
        }
        //wpad host override
        if (!is_array($config['unbound']['hosts'])) {
        	$config['unbound']['hosts'] = array();
        }
        $a_hosts = &$config['unbound']['hosts'];
        $existewpadho = false;
        $configinhow = false;
        foreach ($a_hosts as $sec) {
           if (strpos($sec['host'], "wpad") !== false) {
             $existewpadho = true;
             $configinhow = true;
           }
        }
        
        $config = parse_config(true);
        $unboundadvanced = &$config['unbound']['custom_options'];
        $advanced = base64_decode($unboundadvanced);
        $openservices = false;
        
        if ($existewpadho && $configinhow) $msg = " - Already exists wpad host override: wpad <--> " . 
          gethostbyname("wpad") . " maybe you have to reconfigure host override in unbound for wpad and restart unbound";
        
        if (!$existewpadho) { //if
         $msg = " - Not exists wpad host override";
         if (fIsIp(gethostbyname("wpad")) && file_exists("/var/unbound/mywpad.conf") && strpos($advanced, "server:include:/var/unbound/mywpad.conf") !== false &&
           strpos($lasips[$choose - 1], gethostbyname("wpad")) !== false ) {
          $msg = " - already exists unbound entrie wpad <->".gethostbyname("wpad")." at custom options: server:include:/var/unbound/mywpad.conf";
          $existewpadho = true;
          $openservices = false;
          }
        
        if (fIsIp(gethostbyname("wpad")) && file_exists("/var/unbound/mywpad.conf") && strpos($advanced, "server:include:/var/unbound/mywpad.conf") !== false &&
           strpos($lasips[$choose - 1], gethostbyname("wpad")) === false ) {
          $msg = " - already exists unbound entrie at custom options: server:include:/var/unbound/mywpad.conf wpad <->".gethostbyname("wpad")." But is diferentet to Interface IP. After you must restart unbound ";
          $existewpadho = false;
          $openservices = true;
          } 
        
          if (!fIsIp(gethostbyname("wpad")) && file_exists("/var/unbound/mywpad.conf") && strpos($advanced, "server:include:/var/unbound/mywpad.conf") !== false ) {
          $msg = " - Not exists wpad host entrie in unbound and already exists unbound custom options: server:include:/var/unbound/mywpad.conf, you must restart unbound";
          $existewpadho = false;
          $openservices = true;
          }
        } //if
        
        if (!$execute) {
        $section->addInput(new Form_Checkbox(
        	'wpadhostoverride',   // checkbox name (id)
        	'WPAD Host Override', // checkbox label
        	'WPAD Host Override in Unbound: '. "$msg", // checkbox text
        	 !$existewpadho  //$pconfig['backupnginx'] checkbox initial value
        ));
        
        /*
        if ($openservices) {
          $section->addInput(new Form_Button(
            'openservices',
            'Open Services',
            "/status_services.php"
          ));
        }
        */
        }
        
        if (!$execute) {
        $section->addInput(new Form_Input(
          'cadenawpadho',
        	'WPAD Host Override now/after:',
        	'text',
        	"Now: wpad <--> " . gethostbyname("wpad") . " . After: wpad <--> " . $lasips[$choose - 1]
        ))->setHelp("WPAD Host Override");
        }
        
        if (!$existewpadho && $execute) { 
          //print_r("No existe Host Override wpad \n");
          $wpadov = "local-data: ".'"'."wpad.".$config['system']['domain']." "."A"." ".$lasips[$choose - 1].'"'."\r\n";
          $wpadov .= "local-data: ".'"'."wpad"." "."A"." ".$lasips[$choose - 1].'"'."\r\n";
          // local-data: "wpad.localdomain.local A 10.10.0.254"
          // local-data: "wpad A 10.10.0.254"
          //crear fichero /var/unbound/mywpad.conf
          file_put_contents("/var/unbound/mywpad.conf", $wpadov);
          //Añadir server:include:/var/unbound/mywpad.conf en unbound advanced
          // / var/unbound/unbound.conf
          $config = parse_config(true);
          $unboundadvanced = &$config['unbound']['custom_options'];
          $advanced = base64_decode($unboundadvanced);
          $escribe = true;
          if (strpos($advanced, "server:include:/var/unbound/mywpad.conf") !== false) $escribe = false;
          if ($escribe) {
            $advanced = base64_decode($unboundadvanced) . "\r\n" . "server:include:/var/unbound/mywpad.conf";
            //echo $advanced . "\n";
            $advanced = base64_encode($advanced);
            $write_advanced_unbound['unboundconfig'] = "{$advanced}";
            //print_r("Añadiendo / Add: server:include:/var/unbound/mywpad.conf en / on: unbound custom options \n");
            $config['unbound']['custom_options'] = $write_advanced_unbound['unboundconfig'];
            write_config();
          }
          //restart unbound
          //print_r("Para aplicar cambios reinicie el servicio unbound - Reload unbound service for apply changes \n");
        }
        
        //dhcp boot 252 options
        $config = parse_config(true);
        $dhcpif = $lasintsys[$choose -1];
        $aux1 = $dhcpif;
        $dhcparray = $config['dhcpd']["{$aux1}"];
        $sienabledhcp = false;
        foreach ($dhcparray as $sec) {
         if (strpos($sec, "enable") !== false) {
           $sienabledhcp = true;
         }
        }
        
        $dhcp252 = false;
        $options252 = false;
        if ($sienabledhcp) {
          //echo "dhcp enable in $dhcpif interface \n";
          $dhcparray = $config['dhcpd']["{$aux1}"]['numberoptions'];
          $j = 0;
            while (!empty($config['dhcpd']["{$aux1}"]['numberoptions']['item'][$j])) {
              $j++;
              if (strpos($config['dhcpd']["{$aux1}"]['numberoptions']['item'][$j], "252") !== false) {
                $options252 = true; $dhcp252 = true;
              }
            }
          //si no existen 252 options add
          if ($options252) {
            //print_r("Ya existen entradas 252 \n");
            $dhcp252 = true;
          } else {
            $dhcp252 = false;
            //get fist item null
            $j = 0;
            while (!empty($config['dhcpd']["{$aux1}"]['numberoptions']['item'][$j])) {
              $j++;
            }
            // add 252 options
            $valor1 = '"'."http://wpad.".$config['system']['domain']."/proxy.pac".'"';
            $valor2 = '"'."http://wpad.".$config['system']['domain']."/wpad.dat".'"';
            $valor3 = '"'."http://wpad.".$config['system']['domain']."/wpad.da".'"';
        
            $config['dhcpd']["{$aux1}"]['numberoptions']['item'][$j]['number'] = 252;
            $config['dhcpd']["{$aux1}"]['numberoptions']['item'][$j]['type'] = "string";
            $config['dhcpd']["{$aux1}"]['numberoptions']['item'][$j]['value'] = base64_encode($valor1);
        
            $config['dhcpd']["{$aux1}"]['numberoptions']['item'][$j+1]['number'] = 252;
            $config['dhcpd']["{$aux1}"]['numberoptions']['item'][$j+1]['type'] = "string";
            $config['dhcpd']["{$aux1}"]['numberoptions']['item'][$j+1]['value'] = base64_encode($valor2);
        
            $config['dhcpd']["{$aux1}"]['numberoptions']['item'][$j+2]['number'] = 252;
            $config['dhcpd']["{$aux1}"]['numberoptions']['item'][$j+2]['type'] = "string";
            $config['dhcpd']["{$aux1}"]['numberoptions']['item'][$j+2]['value'] = base64_encode($valor3);
        
            //$dhcp252 = false;
            //print_r("Adding 252 boot options in interface $aux1 : $valor1 \n");
            //print_r("Adding 252 boot options in interface $aux1 : $valor2 \n");
            //print_r("Adding 252 boot options in interface $aux1 : $valor3 \n");
        
            //write_config();
          }
        } else {
            //echo "dhcp NOT enable in $dhcpif interface \n";
            //$dhcp252 = false;
        }
        
        if (!$sienabledhcp) { $adhcp252 = false; $msg = " - dhcp NOT enable on interface"; }
        if ($sienabledhcp && !$dhcp252) { $adhcp252 = true; $msg = " - dhcp enable on interface and Not exist 252 boot dhcp options"; } 
        if ($sienabledhcp && $dhcp252) { $adhcp252 = false; $msg = " - dhcp enable on interfaz and already exists 252 dhcp boot options"; }
        if ($execute && $adhcp252) write_config();
        
        if (!$execute) {
        $section->addInput(new Form_Checkbox(
        	'dhcp252',   // checkbox name (id)
        	'DHCP 252 Boot Options', // checkbox label
        	'DHCP 252 Boot Options'."$msg", // checkbox text
        	 $adhcp252  //$pconfig['backupnginx'] checkbox initial value
        ));
        }
        
        //proxy pac
        $proxyport = $config['installedpackages']['squid']['config'][0]['proxy_port'];
        $auxw = "PROXY wpad." . $config['system']['domain']. ":$proxyport";
        $world = _($auxw);
        $world2 = _($config['system']['domain']);
        $world3 = _($lasips[$choose -1]);
        $world4 = _($lasmasks[$choose -1]);
        
        $fecha = date("Y").date("m").date("d").date('Hi');
        $backupproxypac = $fecha."proxy.pac.origin";
        $dobackupproxypac = true;
        
        if (!$execute) {
        $section->addInput(new Form_CheckBox(
          'backupproxypac',
          'Backup proxy.pac',
          'Backup /usr/local/www/nginx-dist/proxy.pac -> ' . "/usr/local/www/nginx-dist/$backupproxypac",
          $dobackupproxypac
        ));
        }
        
         if (file_exists("/usr/local/www/nginx-dist/proxy.pac")){
          //backup/copiar nginx.conf -> ngnix.conf.origin
          $fecha = date("Y").date("m").date("d").date('Hi');
          $backupproxypac = $fecha."proxy.pac.origin";
          if ($execute && $dobackupproxypac) copy("/usr/local/www/nginx-dist/proxy.pac", "/usr/local/www/nginx-dist/$backupproxypac");
        }
        
        $proxypacnew = <<<eof<br>function FindProxyForURL(url, host) {
        //var wpad = "PROXY wpad.localdomain.local:3128";
        var wpad = "$world";
        host = host.toLowerCase();
        var hostIP = dnsResolve(host);
        if (hostIP == 0) return wpad; 
        if (isPlainHostName(host)) return "DIRECT";
        if (shExpMatch(host, ".local")) return "DIRECT";
        //mi dominio localdomain.local;
        //if (shExpMatch(host, ".localdomain.local")) return "DIRECT";
        if (shExpMatch(host, ".$world2")) return "DIRECT";
        //redes privadas;
        if (isInNet(dnsResolve(host), "127.0.0.0", "255.0.0.0")) return "DIRECT";
        if (isInNet(dnsResolve(host), "10.0.0.0", "255.0.0.0")) return "DIRECT";
        if (isInNet(dnsResolve(host), "10.0.0.0", "255.255.0.0")) return "DIRECT";
        if (isInNet(dnsResolve(host), "10.0.0.0", "255.255.255.0")) return "DIRECT";
        //mi red privada;
        if (isInNet(dnsResolve(host), "$world3", "$world4")) return "DIRECT";
        //end mi red privada;
        if (isInNet(dnsResolve(host), "192.168.0.0", "255.255.0.0")) return "DIRECT";
        if (isInNet(dnsResolve(host), "192.168.0.0", "255.255.255.0")) return "DIRECT";
        if (isInNet(dnsResolve(host), "172.16.0.0", "255.240.0.0")) return "DIRECT";
        if (shExpMatch(host, "fe80::*")) return "DIRECT";
        if (shExpMatch(url, "http:*")) return wpad;
        if (shExpMatch(url, "https:*")) return wpad;
        return wpad;
        }
        EOF;
        
        if ($execute) {
          file_put_contents("/usr/local/www/nginx-dist/proxy.pac", $proxypacnew);
          shell_exec("/bin/ln -s /usr/local/www/nginx-dist/proxy.pac /usr/local/www/nginx-dist/wpad.dat");
          shell_exec("/bin/ln -s /usr/local/www/nginx-dist/proxy.pac /usr/local/www/nginx-dist/wpad.da");
        }
        
        if (!$execute) {
        $section->addInput(new Form_Textarea(
        	'proxypac',
        	'proxy.pac',
        	$proxypacnew
        ))->setHelp("The **proxy.pac** file.");
        }
        
        $runatboot = false;
        $k = 0;
        while (!empty($config['system']['shellcmd']["$k"])) {
          if (strpos($config['system']['shellcmd']["$k"], "/usr/local/etc/rc.d/nginx onestart") !== false) {
            $runatboot = true;
          }
          $k++;
        }
        if (!$runatboot) {
          //print_r("Añadiendo al inicio del sistema / Add at system boot: /usr/local/etc/rc.d/nginx onestart \n");
          $msg = "Se añadirá al inicio del sistema / It will add at system boot: /usr/local/etc/rc.d/nginx onestart";
          $config['system']['shellcmd'][$k] = "/usr/local/etc/rc.d/nginx onestart";
          if ($execute) write_config();
        } else {
            //print_r("Ya existe al inicio del sistema / Exist at boot system: /usr/local/etc/rc.d/nginx onestart \n");
            $msg = "Ya existe al inicio del sistema / Already Exist at boot system: /usr/local/etc/rc.d/nginx onestart";
        }
        
        if (!$execute) {
        
        $section->addInput(new Form_Checkbox(
        	'runatboot',   // checkbox name (id)
        	'Run at Boot WPAD', // checkbox label
        	'Run at Boot WPAD: '."$msg", // checkbox text
        	 !$runatboot  //$pconfig['backupnginx'] checkbox initial value
        ));
        
        $form->add($section);
        
        $laeleccion = $choose;
        $referer = "/mywpad.php?elchoose=$laeleccion&execute=true";
        $btncncl = new Form_Button(
            'apply',
            'Apply',
            $referer
        );
        
        $btncncl->removeClass('btn-primary')->addClass('btn-danger');
        
        $form->addGlobal($btncncl);
        
        print $form;
        }
        
        if ($execute) {
        $form->add($section);
        
        exec("/usr/local/etc/rc.d/nginx oneconfigtest 2> /tmp/testnginx.tmp", $output, $return_var);
        $lanzarnginx = shell_exec("/usr/local/etc/rc.d/nginx onestart");
        $test = shell_exec("cat /tmp/testnginx.tmp");
        $mywpadconf = shell_exec("cat /var/unbound/mywpad.conf");
        $test = $test . "\r\n" . $mywpadconf;
        
        $section->addInput(new Form_Textarea(
        	'testnginx',
        	'Test: ',
        	"$test"
        ))->setHelp("Test nginx.conf, and /var/unbound/mywpad.conf");
        
        $section->addInput(new Form_Input(
          'msgrestart',
        	'Restart Unbound and dhcpd Services',
        	'text',
        	"Now: wpad <--> " . gethostbyname("wpad") . " . After restart service unbound: wpad <--> " . $lasips[$choose - 1]
        ))->setHelp("Restart Unbound and dhcpd Services");
        
        $section->addInput(new Form_Button(
            'openservices',
            'Open Services',
            '/status_services.php'
          ));
        
        print $form;
        }
        function fIsIp($vip) {
          if (!filter_var($vip, FILTER_VALIDATE_IP) === false) { return true; } else { return false; }
        }
        
        ?></eof<br></eof<br> 
        

        Salu2

        Javier Castañón
        Técnico de comunicaciones, soporte y sistemas.

        Mi web: https://javcasta.com/

        Soporte scripting/pfSense https://javcasta.com/soporte/

        1 Reply Last reply Reply Quote 0
        • W Offline
          will23b
          last edited by

          Saludos

          Estimado tengo varias consultas:

          • con esta configuración es necesario colocar en el dns resolver las demas configuraciones?
          • hay que crear los ficheros wpad.dat, proxy.pac y demas?

          estoy un poco confundido, ya que ejecute pero a la hora de navegar en el pc cliente no navega….pero en los logs si le asigna el wpad.da

          1 Reply Last reply Reply Quote 0
          • J Offline
            javcasta
            last edited by

            Hola

            Tengo todas las respuestas en:

            Origen del script en su versión cli (donde voy desgranando el proceso):
            https://forum.pfsense.org/index.php?topic=112715.0

            Hilo donde explico WPAD revertiendo la gui a HTTP y sin revertir la gui a HTTP:
            https://forum.pfsense.org/index.php?topic=109927.0

            El script crea si no existe una entrada en unbound para el host wpad
            El proxy.pac lo crea el script (así como los enlaces simbólicos a wpad.dat y wpad.da) , como mucho puedes editarlo y modificarlo
            a tu conveniencia

            Tan solo hay que reiniciar los servicios unbound y dhcpd para que wpad esté operativo.

            Las reglas del firewall si buscas en los links sabras como configurarlas.

            E imagino que tienes squid instalado en modo NO transparente …

            Y creo que ya he posteado suficiente sobre el tema, tan solo hay que leer y usar el buscador :)

            Salu2

            Javier Castañón
            Técnico de comunicaciones, soporte y sistemas.

            Mi web: https://javcasta.com/

            Soporte scripting/pfSense https://javcasta.com/soporte/

            1 Reply Last reply Reply Quote 0
            • A Offline
              acriollo
              last edited by

              Muy buen aporte.

              1 Reply Last reply Reply Quote 0
              • W Offline
                will23b
                last edited by

                Excelente, gracias por las aclaraciones, ya esta implementado …..excelente aporte.

                1 Reply Last reply Reply Quote 0
                • W Offline
                  will23b
                  last edited by

                  Realizando la implementación me surgió un problema, realizo las pruebas con los navegadores: firefox, chrome y el internet explorer; en firefox y en el iexplorer funciona bien, me detecta la navegación y realiza los bloqueos el squid.

                  En el chrome, sucede que cargo la pagina se queda tratando de conectar pero al final no carga nada; pero en los log del pfsense si llegan las peticiones y se activa el wpad, pero la pagina nunca carga, ya intente con varios sitios y nada. Les ha pasado esto??

                  La configuración que tengo es la que he seguido en los manuales, las reglas del fw están para que el control del proxy. Otra novedad que se me presento es al implementar tambien el squidGuard, no me bloquea, o no se lo implementa con el wpad.

                  1 Reply Last reply Reply Quote 0
                  • W Offline
                    will23b
                    last edited by

                    Ya solucioné lo del chrome…..

                    Pero si necesitaría ayuda con lo del squidGuard

                    1 Reply Last reply Reply Quote 0
                    • W Offline
                      will23b
                      last edited by

                      Resuelto el problema con el squidGuard.

                      1 Reply Last reply Reply Quote 0
                      • J Offline
                        javcasta
                        last edited by

                        Hola

                        Me alegro will23b.

                        Y si resuelves un problema, postea como lo hicistes, así el que tenga tu mismo problema y busque en el foro le servirá de ayuda. :)

                        Salu2

                        Javier Castañón
                        Técnico de comunicaciones, soporte y sistemas.

                        Mi web: https://javcasta.com/

                        Soporte scripting/pfSense https://javcasta.com/soporte/

                        1 Reply Last reply Reply Quote 0
                        • W Offline
                          will23b
                          last edited by

                          Saludos

                          Estoy haciendo pruebas con los telefonos android, actualmente no me reparte el proxy y no navegan…..si han tenido el mismo problema por favor ayuda.

                          1 Reply Last reply Reply Quote 0
                          • J Offline
                            javcasta
                            last edited by

                            Hola

                            En ambientes de redes educativas, como universidades, que suelen usar proxy con autenticación (o no) y wpad, muchos usuarios de Android usan Drony:

                            https://play.google.com/store/apps/details?id=org.sandroproxy.drony&hl=es

                            ★ Root NOT needed ★
                            Proxy that can operate with proxy authentications.
                            Android OS has just proxy with no authentication.
                            So this app can help you with your corporate/university/school network environment.

                            Supports digest, windows (ntlm), basic authentication. HTTP,HTTPS,SOCKS4a,SOCKS5 type of

                            Salu2

                            Javier Castañón
                            Técnico de comunicaciones, soporte y sistemas.

                            Mi web: https://javcasta.com/

                            Soporte scripting/pfSense https://javcasta.com/soporte/

                            1 Reply Last reply Reply Quote 0
                            • J Offline
                              javerleo
                              last edited by

                              Gracias por tu aporte Javier.

                              Ahorra mucho tiempo el script. Antes hacía todo manualmente.

                              Solo tengo una duda. ¿Por qué en el script no se agrega una entrada mime para la extensión pac, como sí se hace para las extensiones dat y da?

                              Mis respetos.

                              –-----------
                              God is my best friend

                              1 Reply Last reply Reply Quote 0
                              • J Offline
                                javerleo
                                last edited by

                                Gracias a javcasta por este aporte. Sin embargo, el día de hoy el script no funciona correctamente con la versión versión 2.4.4 y posteriores, en la que se usa PHP 7 y se produce un error fatal que impide la carga de la página. Este es el error:

                                HP Fatal error: Uncaught Error: Cannot use string offset as an array in /usr/local/www/mywpad.php:347

                                Pregunto si algún desarrollador PHP puede revisarlo para hacer la corrección necesaria. La verdad este script ahorra mucho tiempo en el proceso de configurar WPAD.

                                –-----------
                                God is my best friend

                                1 Reply Last reply Reply Quote 0
                                • First post
                                  Last post
                                Copyright 2025 Rubicon Communications LLC (Netgate). All rights reserved.