PfSense 2.3.x – PhP Cli script – WPADcliSetup.php



  • Hola

    pfSense 2.3.x – PhP Cli script – WPADcliSetup.php

    Un script php-cli (se ejecuta vía shell: ssh) para configurar nginx para que escuche las peticiones WPAD por el puerto 80 y la IP de la interfaz que se elija. Sin tener que revertir la GUI del pfSense a HTTP (manteniendo la seguridad de la GUI con HTTPS)

    El script , en fase alpha, solo configura ngnix.conf (por ahora en esta versión), se supone que se debe tener configurado ya:

    Un host override en unbound para wpad.eldominio.algo <–> ip interfaz donde escucha nginx
        Entradas 252 en el dhcp server: http://wpad.eldominio.algo/proxy.pac y wpad.dat y wpad.da
        Alojado el proxy.pac en “/usr/local/www/nginx-dist/proxy.pac”
        Enlaces simbólicos a wpad.dat y wpad.da con ruta “/usr/local/www/nginx-dist/proxy.pac”

    El script se aloja en una carpeta ( /tmp o /scripts) y se ejecuta vía shell:

    php /tmp/WPADcliSetup.php

    El código:

    #!/usr/local/bin/php
    /*
    WPADcliSetup.php
    by Javier Castañón - https://javcasta.com/ - PIyMenta 2016
    VorumServer 2.0 SecureLAN
    
    ===
    */
    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;
    
    echo "\033[34m################################################## \033[0m \n";
    echo "\033[31m#    Setup ngnix.conf for WPAD v1 alpha  2016    # \033[0m \n";
    echo "\033[34m################################################## \033[0m \n";
    echo "\033[34m#by Javier Castañon.javcasta https://javcasta.com# \033[0m \n";
    echo "\033[34m################################################## \033[0m \n";
    echo "\033[34m################################################## \033[0m \n";
    echo "\033[34m#host WPADcliSetup.php in /tmp or /scripts folder# \033[0m \n";
    echo "\033[34m################################################## \033[0m \n";
    echo "\033[34m#   run via shell: # php /tmp/WPADcliSetup.php   # \033[0m \n";
    echo "\033[34m################################################## \033[0m \n";
    
    //choose IP
    echo "Elige nº para IP & Interfaz para WPAD (normalmente interfaz LAN) \n";
    echo "Choose number for IP & IF for WPAD (ussually LAN interface) \n";
    $lasips = array();
    $ifdescrs = get_configured_interface_with_descr();
    $i = 0;
    foreach ($ifdescrs as $ifdescr => $ifname) {
    $ifinfo = get_interface_info($ifdescr);
    $sichequeado = "";
    if ($ifinfo['status'] == "up" || $ifinfo['status'] == "associated") {
      $i++;
       if (strpos($ifname, "LAN") !== false) { 
         echo $i . " " . "\033[32m".$ifname." - ".$ifinfo['ipaddr']." \033[0m \n";
         $lasips[] = $ifinfo['ipaddr'];
       }
       else { 
         echo $i ." " . $ifname . ' ' . $ifinfo['ipaddr'] . " \033[0m \n";
         $lasips[] = $ifinfo['ipaddr'];
         }
    	}
    } //end foreach
    $choose = readline("Por favor, introduce el nº / Please, enter Number: ");
    echo "Has elegido / Your election is: ". $choose . " - " . $lasips[$choose - 1] . "\n";
    
    //backup/copiar nginx.conf -> ngnix.conf.origin
    $fecha = date("Y").date("m").date("d").date('Hi');
    $backupngnixconf = $fecha."nginx.conf.origin";
    copy("/usr/local/etc/nginx/nginx.conf", "/usr/local/etc/nginx/$backupngnixconf");
    print_r("Backup for /usr/local/etc/nginx/nginx.conf done: $backupngnixconf \n");
    
    //parsear ngnix.conf para que escuche en host - wpad.dominio : IP
    
        $world = _($lasips[$choose - 1]);
        $world2 = _($config['system']['domain']);
    
        $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;
    
        sendfile        on;
        #tcp_nopush     on;
    
        #keepalive_timeout  0;
        keepalive_timeout  65;
    
        server {
            listen      $world:80;
            server_name  wpad.$world2;
            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;
    
    // $str to file /
    file_put_contents("/usr/local/etc/nginx/nginx.conf", $str);
    print_r("/usr/local/etc/nginx/nginx.conf configured for wpad \n");
    $show = shell_exec("/bin/cat /usr/local/etc/nginx/nginx.conf");
    echo $show;
    //run one instance ngninx for wpad
    shell_exec("[ -f /var/run/nginx.pid ] && echo 'OK' > /tmp/ngnix-status.tmp || /usr/local/etc/rc.d/nginx onestart");
    ?></eof<br>
    

    Salu2

    ref: https://www.javcasta.com/pfsense-2-3-x-php-cli-script-wpadclisetup-php/



  • Hola

    Una aclaración: Si se han declarado  los mime-types para .dat y.da en "/usr/local/etc/nginx/mime.types" dará un error.

    Vía el script , ya se declaran los mime-types en en nginx.conf


    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;
        }
    ...

    Salu2



  • Hola

    En pfSense 2.3.x. Si se ha modificado nginx.conf, para el procedimiento de WPAD sin revertir GUI a HTTP.

    Para testear o checkear la sintaxis del fichero de configuración “/usr/local/etc/nginx/nginx.conf”:

    Ya sea vía shell o en Diagnostics > Command Prompt > Execute Shell Command:

    /usr/local/etc/rc.d/nginx oneconfigtest
    

    [2.3.1-RELEASE][root]/scripts: /usr/local/etc/rc.d/nginx oneconfigtest
    Performing sanity check on nginx configuration:
    nginx: the configuration file /usr/local/etc/nginx/nginx.conf syntax is ok
    nginx: configuration file /usr/local/etc/nginx/nginx.conf test is successful

    Salu2

    ref http://www.javcasta.com/pfsense-2-3-x-test-o-check-de-nginx-conf/



  • Hola

    He añadido al script un test de la validez del nginx.conf generado y si es así que lo lance

    He conseguido que el script añada un Host Override para wpad.undominio.algo si no existiese.

    Ahora tengo la pega de que no sé muy bien ¿como reiniciar en pfSense 2.3.x el servicio unbound (DNS Resolver) vía php-cli o bash o shell?

    El código

    #!/usr/local/bin/php
    /*
    WPADcliSetup.php
    by Javier Castañón - https://javcasta.com/ - PIyMenta 2016
    VorumServer 2.0 SecureLAN
    
    ===
    */
    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;
    
    echo "\033[34m################################################## \033[0m \n";
    echo "\033[31m#    Setup ngnix.conf for WPAD v1 alpha  2016    # \033[0m \n";
    echo "\033[34m################################################## \033[0m \n";
    echo "\033[34m#by Javier Castañon.javcasta https://javcasta.com# \033[0m \n";
    echo "\033[34m################################################## \033[0m \n";
    echo "\033[34m################################################## \033[0m \n";
    echo "\033[34m#host WPADcliSetup.php in /tmp or /scripts folder# \033[0m \n";
    echo "\033[34m################################################## \033[0m \n";
    echo "\033[34m#   run via shell: # php /tmp/WPADcliSetup.php   # \033[0m \n";
    echo "\033[34m################################################## \033[0m \n";
    
    //choose IP
    echo "Elige nº para IP & Interfaz para WPAD (normalmente interfaz LAN) \n";
    echo "Choose number for IP & IF for WPAD (ussually LAN interface) \n";
    $lasips = array();
    $ifdescrs = get_configured_interface_with_descr();
    $i = 0;
    foreach ($ifdescrs as $ifdescr => $ifname) {
    $ifinfo = get_interface_info($ifdescr);
    $sichequeado = "";
    if ($ifinfo['status'] == "up" || $ifinfo['status'] == "associated") {
      $i++;
       if (strpos($ifname, "LAN") !== false) { 
         echo $i . " " . "\033[32m".$ifname." - ".$ifinfo['ipaddr']." \033[0m \n";
         $lasips[] = $ifinfo['ipaddr'];
       }
       else { 
         echo $i ." " . $ifname . ' ' . $ifinfo['ipaddr'] . " \033[0m \n";
         $lasips[] = $ifinfo['ipaddr'];
         }
    	}
    } //end foreach
    $choose = readline("Por favor, introduce el nº / Please, enter Number: ");
    echo "Has elegido / Your election is: ". $choose . " - " . $lasips[$choose - 1] . "\n";
    
    //backup/copiar nginx.conf -> ngnix.conf.origin
    $fecha = date("Y").date("m").date("d").date('Hi');
    $backupngnixconf = $fecha."nginx.conf.origin";
    copy("/usr/local/etc/nginx/nginx.conf", "/usr/local/etc/nginx/$backupngnixconf");
    print_r("Backup for /usr/local/etc/nginx/nginx.conf done: $backupngnixconf \n");
    
    //parsear ngnix.conf para que escuche en host - wpad.dominio : IP
    
        $world = _($lasips[$choose - 1]);
        $world2 = _($config['system']['domain']);
    
        $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;
    
        sendfile        on;
        #tcp_nopush     on;
    
        #keepalive_timeout  0;
        keepalive_timeout  65;
    
        server {
            listen      $world:80;
            server_name  wpad.$world2;
            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;
    
    // $str to file /
    file_put_contents("/usr/local/etc/nginx/nginx.conf", $str);
    print_r("/usr/local/etc/nginx/nginx.conf configured for wpad \n");
    $show = shell_exec("/bin/cat /usr/local/etc/nginx/nginx.conf");
    echo "================================= \n";
    echo $show;
    echo "================================= \n";
    echo "Realizando test de nginx.conf / Performing nginx.conf Test \n";
    exec("/usr/local/etc/rc.d/nginx oneconfigtest 2> /tmp/testnginx.tmp", $output, $return_var);
    $test = shell_exec("cat /tmp/testnginx.tmp");
    echo $test." \n";
    //if test ok, run one instance ngninx for wpad
    if (strpos($test, "syntax is ok") !== false && strpos($test, "test is successful") !== false) {
      echo "Test OK \n";
      shell_exec("[ -f /var/run/nginx.pid ] && echo 'OK' > /tmp/ngnix-status.tmp || /usr/local/etc/rc.d/nginx onestart");
    } else {
      echo "Test NO OK \n";
      die();
    } 
    echo "\n";
    //si no existe host override wpad.eldominio.algo --> add Host Override wpad.eldominio.algo <--> La IP
    if (!is_array($config['unbound']['hosts'])) {
    	$config['unbound']['hosts'] = array();
    }
    $a_hosts = &$config['unbound']['hosts'];
    $existewpadho = 0;
    foreach ($a_hosts as $sec) {
       if (strpos($sec['host'], "wpad") !== false) {
         $existewpadho = 1;
       }
    }
    if ($existewpadho == 1) { 
      print_r("Ya existe Host Override wpad \n");
      print_r("wpad <--> ".gethostbyname("wpad")."\n");
    }
    
    //0
    if ($existewpadho == 0) { 
      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) . "\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 ??
      echo "Para aplicar cambios reinicie el servicio unbound / Reload unbound service for apply changes \n";
    }
    //TODO - road map
    // falta implementar proxy.pac,
    //si dhcp server on en interfaz añadir options 252
    //crear enlaces simbólicos a wpad.dat y .da
    ?></eof<br> 
    

    Salu2

    Ref: https://www.javcasta.com/pfsense-2-3-x-php-cli-script-wpadclisetup-php-ii/

    –- add --

    Faltaba unas comillas de cierre en linea

      print_r("Añadiendo / Add: server:include:/var/unbound/mywpad.conf en / on: unbound custom options \n");
    

    corregido :)



  • Hola

    Faltaba unas comillas de cierre en linea

    print_r("Añadiendo / Add: server:include:/var/unbound/mywpad.conf en / on: unbound custom options \n");
    

    corregido :)

    Salu2



  • Hola

    Sigo con la hoja de ruta (road map) del script.

    He añadido:

    Si dhcp server on (enable) en Interface y no existe entrada 252 "http://wpad.eldominio.algo/proxy.pac/proxy.pac" , wpad.dat y wpad.da crearlas

    dhcp enable in opt1 interface
    Adding 252 boot options in interface opt1 : "http://wpad.localdomain.local/proxy.pac"
    Adding 252 boot options in interface opt1 : "http://wpad.localdomain.local/wpad.dat"
    Adding 252 boot options in interface opt1 : "http://wpad.localdomain.local/wpad.da"

    El código añadido:

    //si dhcp server on en Interface y no existe entradas 252 "http://wpad.eldominio.algo/proxy.pac wpad.dat wpad.da" crearlas
    $dhcpif = $lasintsys[$choose -1];
    $aux1 = $dhcpif;
    $dhcparray = $config['dhcpd']["{$aux1}"];
    $sienabledhcp = 0;
    foreach ($dhcparray as $sec) {
     if (strpos($sec, "enable") !== false) {
       $sienabledhcp = 1;
     }
    }
    $options252 = 0;
    if ($sienabledhcp == 1) {
      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 = 1;
          }
        }
      //si no existen 252 options add
      if ($options252 == 1) {
        print_r("Ya existen entradas 252");
      } else {
        //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);
    
        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";
    }
    

    El código completo ( por ahora :) )

    #!/usr/local/bin/php
    /*
    WPADcliSetup.php
    by Javier Castañón - https://javcasta.com/ - PIyMenta 2016
    VorumServer 2.0 SecureLAN
    
    ===
    */
    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);
    
    echo "\033[34m################################################## \033[0m \n";
    echo "\033[31m#    Setup ngnix.conf for WPAD v1 alpha  2016    # \033[0m \n";
    echo "\033[34m################################################## \033[0m \n";
    echo "\033[34m#by Javier Castañon.javcasta https://javcasta.com# \033[0m \n";
    echo "\033[34m################################################## \033[0m \n";
    echo "\033[34m################################################## \033[0m \n";
    echo "\033[34m#host WPADcliSetup.php in /tmp or /scripts folder# \033[0m \n";
    echo "\033[34m################################################## \033[0m \n";
    echo "\033[34m#   run via shell: # php /tmp/WPADcliSetup.php   # \033[0m \n";
    echo "\033[34m################################################## \033[0m \n";
    
    //choose IP
    echo "Elige nº para IP & Interfaz para WPAD (normalmente interfaz LAN) \n";
    echo "Choose number for IP & IF for WPAD (ussually LAN interface) \n";
    $lasips = array();
    $lasinterfaces = array();
    $lasintsys = array();
    $ifdescrs = get_configured_interface_with_descr();
    $i = 0;
    foreach ($ifdescrs as $ifdescr => $ifname) {
    $ifinfo = get_interface_info($ifdescr);
    //$sichequeado = "";
    if ($ifinfo['status'] == "up" || $ifinfo['status'] == "associated") {
      $i++;
       if (strpos($ifname, "LAN") !== false) { 
         echo $i . " " . "\033[32m".$ifname." - ".$ifinfo['ipaddr']." \033[0m \n";
         $lasips[] = $ifinfo['ipaddr'];
         $lasinterfaces[] = $ifname;
         $lasintsys[] = array_search ("$ifname", $ifdescrs);
       }
       else { 
         echo $i ." " . $ifname . ' ' . $ifinfo['ipaddr'] . " \033[0m \n";
         $lasips[] = $ifinfo['ipaddr'];
         $lasinterfaces[] = $ifname;
         $lasintsys[] = array_search ("$ifname", $ifdescrs);
         }
    	}
    } //end foreach
    
    $choose = readline("Por favor, introduce el nº / Please, enter Number: ");
    echo "Has elegido / Your election is: $choose" . $lasinterfaces[$choose - 1] . " " . " - " . $lasips[$choose - 1] . "\n";
    //backup/copiar nginx.conf -> ngnix.conf.origin
    $fecha = date("Y").date("m").date("d").date('Hi');
    $backupngnixconf = $fecha."nginx.conf.origin";
    copy("/usr/local/etc/nginx/nginx.conf", "/usr/local/etc/nginx/$backupngnixconf");
    print_r("Backup for /usr/local/etc/nginx/nginx.conf done: $backupngnixconf \n");
    
    //parsear ngnix.conf para que escuche en host - wpad.dominio : IP
    
        $world = _($lasips[$choose - 1]);
        $world2 = _($config['system']['domain']);
    
        $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;
    
        sendfile        on;
        #tcp_nopush     on;
    
        #keepalive_timeout  0;
        keepalive_timeout  65;
    
        server {
            listen      $world:80;
            server_name  wpad.$world2;
            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;
    
    // $str to file /
    file_put_contents("/usr/local/etc/nginx/nginx.conf", $str);
    print_r("/usr/local/etc/nginx/nginx.conf configured for wpad \n");
    $show = shell_exec("/bin/cat /usr/local/etc/nginx/nginx.conf");
    echo "================================= \n";
    echo $show;
    echo "================================= \n";
    echo "Realizando test de nginx.conf / Performing nginx.conf Test \n";
    exec("/usr/local/etc/rc.d/nginx oneconfigtest 2> /tmp/testnginx.tmp", $output, $return_var);
    $test = shell_exec("cat /tmp/testnginx.tmp");
    echo $test." \n";
    //if test ok, run one instance ngninx for wpad
    if (strpos($test, "syntax is ok") !== false && strpos($test, "test is successful") !== false) {
      echo "Test OK \n";
      shell_exec("[ -f /var/run/nginx.pid ] && echo 'OK' > /tmp/ngnix-status.tmp || /usr/local/etc/rc.d/nginx onestart");
    } else {
      echo "Test NO OK \n";
      die();
    } 
    echo "\n";
    //si no existe host override wpad.eldominio.algo --> add Host Override wpad.eldominio.algo <--> La IP
    if (!is_array($config['unbound']['hosts'])) {
    	$config['unbound']['hosts'] = array();
    }
    $a_hosts = &$config['unbound']['hosts'];
    $existewpadho = 0;
    foreach ($a_hosts as $sec) {
       if (strpos($sec['host'], "wpad") !== false) {
         $existewpadho = 1;
       }
    }
    if ($existewpadho == 1) { 
      print_r("Ya existe Host Override wpad \n");
      print_r("wpad <--> ".gethostbyname("wpad")."\n");
    }
    
    //0
    if ($existewpadho == 0) { 
      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) . "\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");
    }
    //si dhcp server on en Interface y no existe entradas 252 "http://wpad.eldominio.algo/proxy.pac wpad.dat wpad.da" crearlas
    $dhcpif = $lasintsys[$choose -1];
    $aux1 = $dhcpif;
    $dhcparray = $config['dhcpd']["{$aux1}"];
    $sienabledhcp = 0;
    foreach ($dhcparray as $sec) {
     if (strpos($sec, "enable") !== false) {
       $sienabledhcp = 1;
     }
    }
    $options252 = 0;
    if ($sienabledhcp == 1) {
      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 = 1;
          }
        }
      //si no existen 252 options add
      if ($options252 == 1) {
        print_r("Ya existen entradas 252");
      } else {
        //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);
    
        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";
    }
    //TODO - road map
    //crear si no existe proxy.pac -> "/usr/local/www/nginx-dist/proxy.pac"
    //enlaces simbólicos
    //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");
    //obtener proxy port
    //$proxyport = $config['installedpackages']['squid']['config'][0]['proxy_port'];
    //print_r($proxyport."\n");
    //añadir cron cada hora : [ -f /var/run/nginx.pid ] && echo “OK” > /tmp/ngnix-status.tmp || /usr/local/etc/rc.d/nginx onestart
    //reiniciar servicios unbound y dhcp
    //sino existe /var/run/nginx lanzar nginx /usr/local/etc/rc.d/nginx onestart
    //echo "[By Javier Castañon - javcasta - PIyMenta 2016](https://javcasta.com/)";
    ?></eof<br>
    

    Salu2

    –add--

    Modificado, por si ya existe una entrada en dhcp boot options, que obtenga el 1er item nulo para escribir en el la option 252

    $j = 0;
        while (!empty($config['dhcpd']["{$aux1}"]['numberoptions']['item'][$j])) {
          $j++;
        }



  • Hola

    Ahora he añadido al script que implemente el proxy.pac y cree los enlaces simbólicos a wpad.dat y wpad.da

    //crear si no existe proxy.pac -> "/usr/local/www/nginx-dist/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]);
    $proxypac = <<<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;
    //si existe proxy.pac hacemos backup
     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";
      copy("/usr/local/www/nginx-dist/proxy.pac", "/usr/local/www/nginx-dist/$backupproxypac");
      print_r("Backup for /usr/local/www/nginx-dist/proxy.pac done: $backupproxypac \n"); 
    }
    file_put_contents("/usr/local/www/nginx-dist/proxy.pac", $proxypac);
    print_r("/usr/local/www/nginx-dist/proxy.pac for wpad \n");
    $show = shell_exec("/bin/cat /usr/local/www/nginx-dist/proxy.pac");
    echo "================================= \n";
    echo $show;
    echo "================================= \n";
    //enlaces simbólicos
    print_r("Create Links for wpad.dat and wpad.da \n");
    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");</eof<br>
    

    El código completo ( por ahora :) … ya queda menos para que el script esté completo y deje la fase alpha y pase a Beta)

    
    #!/usr/local/bin/php
    /*
    WPADcliSetup.php
    by Javier Castañón - https://javcasta.com/ - PIyMenta 2016
    VorumServer 2.0 SecureLAN
    
    ===
    */
    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);
    
    echo "\033[34m################################################## \033[0m \n";
    echo "\033[31m#    Setup ngnix.conf for WPAD v1 alpha  2016    # \033[0m \n";
    echo "\033[34m################################################## \033[0m \n";
    echo "\033[34m#by Javier Castañon.javcasta https://javcasta.com# \033[0m \n";
    echo "\033[34m################################################## \033[0m \n";
    echo "\033[34m################################################## \033[0m \n";
    echo "\033[34m#host WPADcliSetup.php in /tmp or /scripts folder# \033[0m \n";
    echo "\033[34m################################################## \033[0m \n";
    echo "\033[34m#   run via shell: # php /tmp/WPADcliSetup.php   # \033[0m \n";
    echo "\033[34m################################################## \033[0m \n";
    
    //choose IP
    echo "Elige nº para IP & Interfaz para WPAD (normalmente interfaz LAN) \n";
    echo "Choose number for IP & IF for WPAD (ussually LAN interface) \n";
    $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) { 
         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";
         $lasips[] = $ifinfo['ipaddr'];
         $lasmasks[] = $ifinfo['subnet'];
         $lasinterfaces[] = $ifname;
         $lasintsys[] = array_search ("$ifname", $ifdescrs);
         }
    	}
    } //end foreach
    
    $choose = readline("Por favor, introduce el nº / Please, enter Number: ");
    echo "Has elegido / Your election is: $choose" . $lasinterfaces[$choose - 1] . " " . " - " . $lasips[$choose - 1] . "\n";
    //backup/copiar nginx.conf -> ngnix.conf.origin
    $fecha = date("Y").date("m").date("d").date('Hi');
    $backupngnixconf = $fecha."nginx.conf.origin";
    copy("/usr/local/etc/nginx/nginx.conf", "/usr/local/etc/nginx/$backupngnixconf");
    print_r("Backup for /usr/local/etc/nginx/nginx.conf done: $backupngnixconf \n");
    
    //parsear ngnix.conf para que escuche en host - wpad.dominio : IP
    
        $world = _($lasips[$choose - 1]);
        $world2 = _($config['system']['domain']);
    
        $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;
    
        sendfile        on;
        #tcp_nopush     on;
    
        #keepalive_timeout  0;
        keepalive_timeout  65;
    
        server {
            listen      $world:80;
            server_name  wpad.$world2;
            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;
    
    // $str to file /
    file_put_contents("/usr/local/etc/nginx/nginx.conf", $str);
    print_r("/usr/local/etc/nginx/nginx.conf configured for wpad \n");
    $show = shell_exec("/bin/cat /usr/local/etc/nginx/nginx.conf");
    echo "================================= \n";
    echo $show;
    echo "================================= \n";
    echo "Realizando test de nginx.conf / Performing nginx.conf Test \n";
    exec("/usr/local/etc/rc.d/nginx oneconfigtest 2> /tmp/testnginx.tmp", $output, $return_var);
    $test = shell_exec("cat /tmp/testnginx.tmp");
    echo $test." \n";
    //if test ok, run one instance ngninx for wpad
    if (strpos($test, "syntax is ok") !== false && strpos($test, "test is successful") !== false) {
      echo "Test OK \n";
      shell_exec("[ -f /var/run/nginx.pid ] && echo 'OK' > /tmp/ngnix-status.tmp || /usr/local/etc/rc.d/nginx onestart");
    } else {
      echo "Test NO OK \n";
      die();
    } 
    echo "\n";
    //si no existe host override wpad.eldominio.algo --> add Host Override wpad.eldominio.algo <--> La IP
    if (!is_array($config['unbound']['hosts'])) {
    	$config['unbound']['hosts'] = array();
    }
    $a_hosts = &$config['unbound']['hosts'];
    $existewpadho = 0;
    foreach ($a_hosts as $sec) {
       if (strpos($sec['host'], "wpad") !== false) {
         $existewpadho = 1;
       }
    }
    if ($existewpadho == 1) { 
      print_r("Ya existe Host Override wpad \n");
      print_r("wpad <--> ".gethostbyname("wpad")."\n");
    }
    
    //0
    if ($existewpadho == 0) { 
      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) . "\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");
    }
    //si dhcp server on en Interface y no existe entradas 252 "http://wpad.eldominio.algo/proxy.pac wpad.dat wpad.da" crearlas
    $dhcpif = $lasintsys[$choose -1];
    $aux1 = $dhcpif;
    $dhcparray = $config['dhcpd']["{$aux1}"];
    $sienabledhcp = 0;
    foreach ($dhcparray as $sec) {
     if (strpos($sec, "enable") !== false) {
       $sienabledhcp = 1;
     }
    }
    $options252 = 0;
    if ($sienabledhcp == 1) {
      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 = 1;
          }
        }
      //si no existen 252 options add
      if ($options252 == 1) {
        print_r("Ya existen entradas 252 \n");
      } else {
        //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);
    
        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";
    }
    //crear si no existe proxy.pac -> "/usr/local/www/nginx-dist/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]);
    $proxypac = <<<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;
    //si existe proxy.pac hacemos backup
     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";
      copy("/usr/local/www/nginx-dist/proxy.pac", "/usr/local/www/nginx-dist/$backupproxypac");
      print_r("Backup for /usr/local/www/nginx-dist/proxy.pac done: $backupproxypac \n"); 
    }
    file_put_contents("/usr/local/www/nginx-dist/proxy.pac", $proxypac);
    print_r("/usr/local/www/nginx-dist/proxy.pac for wpad \n");
    $show = shell_exec("/bin/cat /usr/local/www/nginx-dist/proxy.pac");
    echo "================================= \n";
    echo $show;
    echo "================================= \n";
    //enlaces simbólicos
    print_r("Create Links for wpad.dat and wpad.da \n");
    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");
    //TODO - road map
    //añadir cron cada hora : [ -f /var/run/nginx.pid ] && echo “OK” > /tmp/ngnix-status.tmp || /usr/local/etc/rc.d/nginx onestart
    //reiniciar servicios unbound y dhcp
    //sino existe /var/run/nginx lanzar nginx /usr/local/etc/rc.d/nginx onestart
    //crear si no existe <shell_exec>/usr/local/etc/rc.d/nginx onestart en config
    //echo "[By Javier Castañon - javcasta - PIyMenta 2016](https://javcasta.com/)";
    ?></shell_exec></eof<br></eof<br> 
    

    Salu2



  • Hola

    he añadido al script que agregue al config.xml una entrada <shellcmd>(si no existe)

    <shellcmd>/usr/local/etc/rc.d/nginx onestart</shellcmd>
    

    Y creo que ya está todo. Así que el script ya está en fase Beta :)

    El código completo.

    #!/usr/local/bin/php
    /*
    WPADcliSetup.php
    by Javier Castañón - https://javcasta.com/ - PIyMenta 2016
    VorumServer 2.0 SecureLAN
    
    ===
    */
    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);
    
    echo "\033[34m################################################## \033[0m \n";
    echo "\033[31m#    Setup ngnix.conf for WPAD v1 alpha  2016    # \033[0m \n";
    echo "\033[34m################################################## \033[0m \n";
    echo "\033[34m#by Javier Castañon.javcasta https://javcasta.com# \033[0m \n";
    echo "\033[34m################################################## \033[0m \n";
    echo "\033[34m################################################## \033[0m \n";
    echo "\033[34m#host WPADcliSetup.php in /tmp or /scripts folder# \033[0m \n";
    echo "\033[34m################################################## \033[0m \n";
    echo "\033[34m#   run via shell: # php /tmp/WPADcliSetup.php   # \033[0m \n";
    echo "\033[34m################################################## \033[0m \n";
    
    //choose IP
    echo "Elige nº para IP & Interfaz para WPAD (normalmente interfaz LAN) \n";
    echo "Choose number for IP & IF for WPAD (ussually LAN interface) \n";
    $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) { 
         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";
         $lasips[] = $ifinfo['ipaddr'];
         $lasmasks[] = $ifinfo['subnet'];
         $lasinterfaces[] = $ifname;
         $lasintsys[] = array_search ("$ifname", $ifdescrs);
         }
    	}
    } //end foreach
    
    $choose = readline("Por favor, introduce el nº / Please, enter Number: ");
    echo "Has elegido / Your election is: $choose" . $lasinterfaces[$choose - 1] . " " . " - " . $lasips[$choose - 1] . "\n";
    //backup/copiar nginx.conf -> ngnix.conf.origin
    $fecha = date("Y").date("m").date("d").date('Hi');
    $backupngnixconf = $fecha."nginx.conf.origin";
    copy("/usr/local/etc/nginx/nginx.conf", "/usr/local/etc/nginx/$backupngnixconf");
    print_r("Backup for /usr/local/etc/nginx/nginx.conf done: $backupngnixconf \n");
    
    //parsear ngnix.conf para que escuche en host - wpad.dominio : IP
    
        $world = _($lasips[$choose - 1]);
        $world2 = _($config['system']['domain']);
    
        $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;
    
        sendfile        on;
        #tcp_nopush     on;
    
        #keepalive_timeout  0;
        keepalive_timeout  65;
    
        server {
            listen      $world:80;
            server_name  wpad.$world2;
            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;
    
    // $str to file /
    file_put_contents("/usr/local/etc/nginx/nginx.conf", $str);
    print_r("/usr/local/etc/nginx/nginx.conf configured for wpad \n");
    $show = shell_exec("/bin/cat /usr/local/etc/nginx/nginx.conf");
    echo "================================= \n";
    echo $show;
    echo "================================= \n";
    echo "Realizando test de nginx.conf / Performing nginx.conf Test \n";
    exec("/usr/local/etc/rc.d/nginx oneconfigtest 2> /tmp/testnginx.tmp", $output, $return_var);
    $test = shell_exec("cat /tmp/testnginx.tmp");
    echo $test." \n";
    //if test ok, run one instance ngninx for wpad
    if (strpos($test, "syntax is ok") !== false && strpos($test, "test is successful") !== false) {
      echo "Test OK \n";
      shell_exec("[ -f /var/run/nginx.pid ] && echo 'OK' > /tmp/ngnix-status.tmp || /usr/local/etc/rc.d/nginx onestart");
    } else {
      echo "Test NO OK \n";
      die();
    } 
    echo "\n";
    //si no existe host override wpad.eldominio.algo --> add Host Override wpad.eldominio.algo <--> La IP
    if (!is_array($config['unbound']['hosts'])) {
    	$config['unbound']['hosts'] = array();
    }
    $a_hosts = &$config['unbound']['hosts'];
    $existewpadho = 0;
    foreach ($a_hosts as $sec) {
       if (strpos($sec['host'], "wpad") !== false) {
         $existewpadho = 1;
       }
    }
    if ($existewpadho == 1) { 
      print_r("Ya existe Host Override wpad \n");
      print_r("wpad <--> ".gethostbyname("wpad")."\n");
    }
    
    //0
    if ($existewpadho == 0) { 
      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) . "\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");
    }
    //si dhcp server on en Interface y no existe entradas 252 "http://wpad.eldominio.algo/proxy.pac wpad.dat wpad.da" crearlas
    $dhcpif = $lasintsys[$choose -1];
    $aux1 = $dhcpif;
    $dhcparray = $config['dhcpd']["{$aux1}"];
    $sienabledhcp = 0;
    foreach ($dhcparray as $sec) {
     if (strpos($sec, "enable") !== false) {
       $sienabledhcp = 1;
     }
    }
    $options252 = 0;
    if ($sienabledhcp == 1) {
      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 = 1;
          }
        }
      //si no existen 252 options add
      if ($options252 == 1) {
        print_r("Ya existen entradas 252 \n");
      } else {
        //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);
    
        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";
    }
    //crear si no existe proxy.pac -> "/usr/local/www/nginx-dist/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]);
    $proxypac = <<<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;
    //si existe proxy.pac hacemos backup
     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";
      copy("/usr/local/www/nginx-dist/proxy.pac", "/usr/local/www/nginx-dist/$backupproxypac");
      print_r("Backup for /usr/local/www/nginx-dist/proxy.pac done: $backupproxypac \n"); 
    }
    file_put_contents("/usr/local/www/nginx-dist/proxy.pac", $proxypac);
    print_r("/usr/local/www/nginx-dist/proxy.pac for wpad \n");
    $show = shell_exec("/bin/cat /usr/local/www/nginx-dist/proxy.pac");
    echo "================================= \n";
    echo $show;
    echo "================================= \n";
    //enlaces simbólicos
    print_r("Create Links for wpad.dat and wpad.da \n");
    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");
    //runt at boot
    //<shellcmd>/usr/local/etc/rc.d/nginx onestart</shellcmd>
    $runatboot = 0;
    $k = 0;
    while (!empty($config['system']['shellcmd']["$k"])) {
      if (strpos($config['system']['shellcmd']["$k"], "/usr/local/etc/rc.d/nginx onestart") !== false) {
        $runatboot = 1;
      }
      $k++;
    }
    if ($runatboot == 0) {
      print_r("Añadiendo al inicio del sistema / Add at system boot: /usr/local/etc/rc.d/nginx onestart \n");
      $config['system']['shellcmd'][$k] = "/usr/local/etc/rc.d/nginx onestart";
      write_config();
    } else {
        print_r("Ya existe al inicio del sistema / Exist at boot system: /usr/local/etc/rc.d/nginx onestart \n");
    }
    print_r("Conveniente añadir cron cada hora : [ -f /var/run/nginx.pid ] && /bin/echo 'OK' > /tmp/ngnix-status.tmp || /usr/local/etc/rc.d/nginx onestart \n");
    print_r("Conveniente: reiniciar servicios unbound y dhcp \n");
    //echo "[By Javier Castañon - javcasta - PIyMenta 2016](https://javcasta.com/)";
    ?></eof<br></eof<br>
    

    Salu2

    ref: https://www.javcasta.com/pfsense-2-3-x-php-cli-script-wpadclisetup-php-iv/
    download: http://www.javcasta.com/?smd_process_download=1&download_id=29762</shellcmd>



  • has probado "System_Patches"



  • Hermano me puedes ayudar con mi pfsense en esa configuracion?



  • Amigo, me hizo que mi configuración como se le enseñó, sin embargo tienen problemas con las pantallas de squid y squidgard como sgerror.php y otras pantallas que se encuentran en la carpeta www, que no son accesibles … para que la pantalla muestra 404 Not Found. ¿Cómo resolver este problema?



  • @vazjunior:

    Amigo, me hizo que mi configuración como se le enseñó, sin embargo tienen problemas con las pantallas de squid y squidgard como sgerror.php y otras pantallas que se encuentran en la carpeta www, que no son accesibles … para que la pantalla muestra 404 Not Found. ¿Cómo resolver este problema?

    Tambem estou com o mesmo problema  :'(



  • Hola

    Yo usaria la versión más avanzada y con GUI, de ese script: https://forum.pfsense.org/index.php?topic=113441.0

    Pero sin olvidar de quitar, si se hubiesen añadido, los mime types .pac .dat .da de /usr/local/etc/nginx/mime.types-dist y  /usr/local/etc/nginx/mime.types , ya que el script define esos mime-typ en en  /usr/local/etc/nginx/nginx.conf

    En mi squidGuard yo lo tengo configurado:

    Common ACL > Redirect mode > ext url move (enter URL) >
    http://wpad.localdomain.local/my-no-autorizado.html

    Y no tengo problemas.

    Salu2



  • Hola

    El código de /usr/local/www/nginx-dist/my-no-autorizado.html

    http://wpad.localdomain.local/my-no-autorizado.htmlhttp://wpad.TUDOMINIO.ALGO/my-no-autorizado.html )

    
    <title>Error</title>
    
    # FORBIDDEN.
    
    ACCESO DENEGADO
    
    PONGASE EN CONTACTO CON SU ADMDOR DE RED SI LO CONSIDERA NECESARIO.
    
    [admin@undominio.com](mailto:admin@lundominio.com).
    
    

    Al correr WPAD en una instancia para HTTP (NO HTTPS) en el dir /usr/local/www/nginx-dist/ , no tiene definido PhP, y no puede ejecutar php. Así que cuando squidGuard redirige a HTTP (NO HTTPS) un fichero php no se ejecutará se descargará.

    Así que mi solución  es definir en squidGuard usar una redirección a una página de contenido estático (html) ante error o prohibición:

    Common ACL >
    Redirect mode >
    ext url move (enter URL) >

    http://wpad.localdomain.local/my-no-autorizado.html

    Salu2



  • Hola

    En este hilo del foro en Portugues:

    Página de erro do SquidGuard customizada | Nova instancia NGINX (suporte PHP)

    muestran como lanzar una nueva instancia de nginx con soporte PhP para la página de error de squidGuard

    https://forum.pfsense.org/index.php?topic=115653.0

    No lo he probado, pero pinta bastante bien :)

    Salu2





  • @vazjunior:

    https://forum.pfsense.org/index.php?topic=114686.msg637207#msg637207

    Hola - Olá

    Buen trabajo vazjunior. - bom trabalho vazjunior.

    Gracias por compartir - Obrigado por compartilhar :)

    Cumprimentos - Salu2



  • Saludos Francisco Javier Castañon. He ejecutado tu archivo mywpad.php en pfsense y aplique lo siguiente:
    1- Cree un alias llamado wpad con la ip del pfsense (192.168.100.1)
    2- Cree un puerto llamado Pproxy con el puerto 3028 (Aqui tengo una duda si colocar el puerto del squid 3128 o 3028 como leí en un foro)
    3- En DNS resolver cree un Host Overrides llamado wpad con dominio wpad.ve Ip: 192.168.100.1
    4- He creado las siguientes reglas:
    States  Protocol Source Port Destination Port Gateway  Queue Schedule Description

    0/0 B    IPv6 *  LAN net * * * * none Default allow LAN IPv6 to any rule
    0/0 B    IPv4 TCP 192.168.100.1 80 (HTTP) * * * none
    1/42.24 MiB  IPv4 * LAN net * * * * none Default allow LAN to any rule
    0/0 B    IPv4 ICMP echoreq LAN net * * * *  none  ICMP echo request
    0/0 B    IPv4 ICMP echorep LAN net * * * * none  ICMP echo reply
    0/0 B    IPv4 TCP/UDP LAN net * wpad 53 (DNS) * none   DNS
    0/0 B    IPv4 TCP LAN net * wpad Pproxy * none   PROXY
    0/0 B    IPv4 * LAN net * * * * none   NO SIN PROXY

    5- He configurado un equipo con deteccion automatica del proxy pero que otras configuraciones me hacen falta para que el equipo no acceda a las paginas no permitidas..? Gracias por tus buenos aportes amigo.



  • Hola

    mywpad.php es un script php para GUI, es decir, no para ser ejecutado via shell, sino desde navegador:

    https://forum.pfsense.org/index.php?topic=113441.0
    http://www.javcasta.com/pfsense-2-3-x-mywpad-mywpad-php/

    Obviamente para la regla del firewall el puerto a permitir es el del proxy, si usas tcp3128 en squid, pues ese.

    El override en dns resolver ya lo crea el script, así como el proxy.pac, etc, leete los links

    Salu2



  • Hola amigo, excelente aporte con tu script…

    He seguido tus manuales y son geniales, aún así sigo sin lograr echar a andar el wpad...

    Veo que pones para una red que consta de una sola LAN  y ahí es donde me enredo...

    Yo cuento con LAN... en la cual no corro nada directamente, todo corre en VLANS y estoy batallando para echarlo a andar..

    He puesto tu script sobre la lan, haciendo las modificaciones siguientes...

    1.- en el archivo de nginx.conf tengo la duda del puerto de escucha... puse la LAN 192.168.1.1:80

    pero debo poner las otras ips de las VLAN ??? ej Listen 192.168.14.1:80 como adicional ??

    2. Cada vlan cuenta con su DHCP, supongo que debo poner los valores de 252 para cada DHCP
    3. en los archivos de proxy.pac, supongo que también debo agregar en la parte de redes privadas las redes de las vlan
    4.-  si intento que la VLAN 14 vea a la LAN para poder ver al ngnix, no me da el archivo proxy.pac

    Qué me sugieres para un entorno con vlans '?

    De ante mano gracias.