Squid страница ошибки

  • Goal: To alter the error pages layouts and content generated by
    Squid.
  • Status: complete.
  • Version: 2.1
  • Developer: Unknown.

🔗 Details

Squid lets you customize your error messages. The source distribution
includes error messages in different languages.

From Squid 3.1:

  • CSS hooks are available for display redesign and coloring.
  • Language translations are done by default automatically when
    language pages are installed. See Translations Project
    for more details on those.

For older Squid you can select the language with the configure option
–enable-err-language=lang.

If needed, you can make a copy and re-write the error message template
files in any version.

🔗 deny_info URL codes for embedding

Squid-2.1 toSquid-3.1
only provide this macro code:

  • %s
    Absolute URL requested by client

Squid-3.2 adds URL templating codes:

  • %a
    User identity
  • %d
    seconds elapsed since request received (not yet implemented)
  • %e
    errno
  • %E
    strerror()
  • %h
    Squid public hostname
  • %H
    server host name
  • %i
    client IP address
  • %I
    server IP address (NP: upper case i)
  • %M
    Request Method
  • %o
    Message returned by external ACL helper
  • %p
    URL port number
  • %P
    Protocol
  • %R
    URL path requested.
  • %S
    Squid version signature.
  • %s
    Absolute URL requested by client
  • %t
    local time
  • %T
    UTC
  • %U
    Absolute URL without password. Uses * instead of path for CONNECT
    requests.
  • %u
    Absolute URL with password. May be missing path on CONNECT requests.
  • %w
    cachemgr email address

🔗 ERR_* template codes for embedding

This list describes the macro codes which Squid will replace in the
error response messages, and what details will be inserted:

  • %a
    User identity
  • %B
    URL with FTP %2f hack
  • %c
    Squid error code
  • %d
    seconds elapsed since request received (not yet implemented)
  • %D
    Squid-generated error details. May contain other error page
    formatting codes. Currently only TLS/SSL connection failures are
    detailed. For example, %D in a customized
    ERR_SECURE_CONNECT_FAIL response may be expanded into “The host
    name you are connecting to (foo.com) does not match any of the
    certificate names (foo.org, foo.net)…”). Supported since
    Squid-3.2.
    See also: application-level error code (%x) and system level error
    code/detail (%e/%E).
  • %e
    errno
  • %E
    strerror()
  • %f
    FTP request line
  • %F
    FTP reply line
  • %g
    FTP server message
  • %h
    cache hostname
  • %H
    server host name
  • %i
    client IP address
  • %I
    server IP address
  • %l
    Local site CSS stylesheet
  • %L
    contents of err_html_text config option
  • %M
    Request Method
  • %m
    Error message returned by external auth helper
  • %o
    Message returned by external acl helper
  • %p
    URL port number
  • %P
    Protocol
  • %R
    Full HTTP Request
  • %S
    squid default signature
  • %s
    caching proxy software with version
  • %t
    local time
  • %T
    UTC time
  • %U
    URL without password
  • %u
    URL with password
  • %W
    Extended error page data URL-encoded for mailto links.
  • %w
    cachemgr email address
  • %x
    Application-level error name or identifier (e.g.,
    X509_V_ERR_UNABLE_TO_GET_CRL). Currently only supported for
    SSL certificate validation errors. See also: system-level error
    code/detail (%e/%E) and application-level error detail (%D).
  • %z
    DNS server error message
  • %Z
    Message generated during the process which failed. May be
    ASCII-formatted. Use within HTML PRE tags.

🔗 Custom error pages not displayed for HTTPS

HTTPS uses HTTP CONNECT messages to relay through a proxy. Due to
browser behaviour handling these CONNECT messages (described in
https://bugzilla.mozilla.org/show_bug.cgi?id=479880) any custom
error page produced by the proxy is ignored and a generic browser page
displayed instead.

Usually this browser page mentions connection faulure or other such
irrelevant details.

In fact any response other than 200 OK is completely dropped by the
browser and the same browser template page displayed. This can lead to
some very weird authentication problems when using HTTPS through an
authenticated proxy as well for authentication schemes where the 407
message body has relevance.

Categories: Feature

Navigation: Site Search,
Site Pages,
Categories, 🔼 go up

imageПосле того как мы начнём в боевом режиме использовать прокси-сервер Squid3, возможно одна из первых вещей, которые захочется сделать – это кастомизация веб-страниц, возвращаемых прокси-сервером при разного рода ошибках доступа к запрашиваемым веб-ресурсам. В целом дизайн страниц ошибок в конфигурации по умолчанию в Squid3 на мой взгляд намного приятней, чем в том же Squid2 и поэтому, по большому счету, необходимости в какой-то сильной кастомизации нет. И самое простое здесь, что мы можем сделать, для того чтобы как-то приблизить этот дизайн к корпоративному – заменить логотип Squid, используемый на всех таких страницах на эмблему компании. Давайте рассмотрим эту нехитрую процедуру.

Для начала создаём новый логотип в формате png. При необходимости очищаем фон изображения с помощью онлайн-сервиса Photo editor online как описано например в заметке — Как сделать прозрачный фон у картинки.

Передаём получившийся графический файл логотипа, например это будет файл SBS-Logo.png с компьютера под управлением Windows на Linux-сервер (в нашем примере KOM-AD01-GW10). Сделать это можно например по протоколу SSH (ранее мы уже запустили службу сервера OpenSSH на KOM-AD01-GW10) с помощью утилиты WinSCP или PSCP. Передадим файл сначала в домашний каталог пользователя /home/user/ (или ~ для краткости):

C:\Tools\PuTTy\pscp -scp C:\Temp\My-Logo.png user@KOM-AD01-GW10:~/My-Logo.png

Указанный файл логотипа нам нужно сделать доступным по протоколу HTTP всем пользователям локальной сети без дополнительной аутентификации. Для этого можно, например, из домашнего каталога /home/user/ переместить файл лого в в каталог /var/www/html/ (корневой каталог веб-сервера Apache2, который доступен нам после его установки в предыдущей части):

sudo mv ~/My-Logo.png  /var/www/html/My-Logo.png

После этого правим ссылку на файл лого в настроечном файле каскадных стилей /etc/squid3/errorpage.css — в секции titles изменяем значение параметра background:

/* Page displayed title area */
#titles {
        margin-left: 15px;
        padding: 10px;
        padding-left: 100px;
        /* background: url('http://www.squid-cache.org/Artwork/SN.png') no-repeat left; */
        background: url('http://KOM-AD01-GW10.holding.com/My-Logo.png') no-repeat left;
}

Перезагружаем Squid:

sudo service squid3 reload

Проверяем результат, например набрав заведомо неверный URL

image

Помимо этого в основном конфигурационном файле Squid3 /etc/squid3/squid.conf есть ряд параметров, которые могут видоизменять формат выводимых данных на страница ошибок. Найти эти параметры можно в разделе ERROR PAGE OPTIONS:

error_directory
error_default_language
err_page_stylesheet
email_err_data
deny_info

Каждый из параметров имеет комментарии объясняющие возможные значения принимаемые в этих параметрах. На приведённом скриншоте страница ошибки принимает вид согласно параметрам настроенным в конфигурационном файле squid.conf, который мы рассмотрели в одной их прошлых заметок.

***

Предыдущие части цикла заметок:

Часть 1. Установка ОС на ВМ Hyper-V Gen2
Часть 2. Настройка диска для кэша Squid
Часть 3. Конфигурация DNS , NTP и установка Squid
Часть 4. Конфигурация Kerberos и NTLM
Часть 5. Конфигурация Squid 3
Часть 6. Настройка Proxy Auto Configuration (WPAD)

Следующие части цикла заметок:

Часть 8. Конфигурация SqStat
Часть 9. Конфигурация LightSquid
Часть 10. Отключаем IPv6

Contents

  1. Squid is ugly

    1. Configuration
    2. Custom pages

Squid is ugly

Squid error pages are ugly, here’s how you can change it.

Configuration

This assumes you already have a squid proxy installation which is up and running.

Squid is serving static pages on errors, denies or on other problematic situations. All those pages can be found in /usr/share/squid/errors/. The pages are stored in folders with language names. Those folders are actually the squid translated pages.

We can change the language squid serves pages by editing /etc/squid/squid.conf configuration file. Find the error_directory directive and change it’s value to the path where your language files are stored.

error_directory /usr/share/squid/errors/Romanian

Ok, but this doesn’t make Squid error pages prettier! To get this issue fixed you can edit every page inside the error pages directory to suit your needs, or, you can use sed!

Custom pages

Make a copy of your language folder first.

mkdir /etc/squid/pages/
cp -r /usr/share/squid/errors/Romanian /etc/squid/pages/

Now cause it is HTML the pages inside that folder are written in, we can use CSS to prettify those. Here’s a simple sed usage to quickly search and replace the default squid error pages CSS tag with some custom CSS:

sed -i 's/<STYLE type="text\/css"><!--BODY{background-color:#ffffff;font-family:verdana,sans-serif}PRE{font-family:sans-serif}--><\/STYLE>/<STYLE type="text\/css"><!--BODY{width:70%; margin: 50px auto;font-family:Georgia,serif; color: #4a4a4a}a:link{color:#cc0000}a:visited{color:#666}--><\/STYLE>/g' *

Now edit again your squid config file and point error_directory to the new location of your error pages. Reload squid:

invoke-rc.d squid reload

Point a browser which uses you squid proxy to some impossible domain name. The resulted error pages are amazingly beautiful! http://img261.imageshack.us/img261/4757/screenshoteroareurlulce.png

You can go further and customize your pages in any way you want. Good luck!

If you do not have a configured error_directory as mentioned, squid -v will report your version of squids compile time options.

The following options will impact the path to the error templates:

  --prefix=PREFIX         install architecture-independent files in PREFIX
                      [/usr/local/squid]
  --datarootdir=DIR       read-only arch.-independent data root [PREFIX/share]
  --datadir=DIR           read-only architecture-independent data [DATAROOTDIR]

The following will impact which error templates are rendered:

  --disable-translation   Prevent Squid generating localized error page
  --disable-auto-locale   This prevents Squid providing localized error pages

So you end up with PREFIX/DATADIR/errors/templates as the default or PREFIX/DATADIR/errors/$locale/

Locale can be based on the clients request if using a recent version of Squid or yours was compiled with --enable-auto-locale for older versions (3.1)

The error_default_language config option can be involved as well.

Then the templates directory is the fallback.

I think this holds true for squid 3.x. Not so sure about 2.x

  • Goal: To alter the error pages layouts and content generated by
    Squid.
  • Status: complete.
  • Version: 2.1
  • Developer: Unknown.

🔗 Details

Squid lets you customize your error messages. The source distribution
includes error messages in different languages.

From Squid 3.1:

  • CSS hooks are available for display redesign and coloring.
  • Language translations are done by default automatically when
    language pages are installed. See Translations Project
    for more details on those.

For older Squid you can select the language with the configure option
–enable-err-language=lang.

If needed, you can make a copy and re-write the error message template
files in any version.

🔗 deny_info URL codes for embedding

Squid-2.1 toSquid-3.1
only provide this macro code:

  • %s
    Absolute URL requested by client

Squid-3.2 adds URL templating codes:

  • %a
    User identity
  • %d
    seconds elapsed since request received (not yet implemented)
  • %e
    errno
  • %E
    strerror()
  • %h
    Squid public hostname
  • %H
    server host name
  • %i
    client IP address
  • %I
    server IP address (NP: upper case i)
  • %M
    Request Method
  • %o
    Message returned by external ACL helper
  • %p
    URL port number
  • %P
    Protocol
  • %R
    URL path requested.
  • %S
    Squid version signature.
  • %s
    Absolute URL requested by client
  • %t
    local time
  • %T
    UTC
  • %U
    Absolute URL without password. Uses * instead of path for CONNECT
    requests.
  • %u
    Absolute URL with password. May be missing path on CONNECT requests.
  • %w
    cachemgr email address

🔗 ERR_* template codes for embedding

This list describes the macro codes which Squid will replace in the
error response messages, and what details will be inserted:

  • %a
    User identity
  • %B
    URL with FTP %2f hack
  • %c
    Squid error code
  • %d
    seconds elapsed since request received (not yet implemented)
  • %D
    Squid-generated error details. May contain other error page
    formatting codes. Currently only TLS/SSL connection failures are
    detailed. For example, %D in a customized
    ERR_SECURE_CONNECT_FAIL response may be expanded into “The host
    name you are connecting to (foo.com) does not match any of the
    certificate names (foo.org, foo.net)…”). Supported since
    Squid-3.2.
    See also: application-level error code (%x) and system level error
    code/detail (%e/%E).
  • %e
    errno
  • %E
    strerror()
  • %f
    FTP request line
  • %F
    FTP reply line
  • %g
    FTP server message
  • %h
    cache hostname
  • %H
    server host name
  • %i
    client IP address
  • %I
    server IP address
  • %l
    Local site CSS stylesheet
  • %L
    contents of err_html_text config option
  • %M
    Request Method
  • %m
    Error message returned by external auth helper
  • %o
    Message returned by external acl helper
  • %p
    URL port number
  • %P
    Protocol
  • %R
    Full HTTP Request
  • %S
    squid default signature
  • %s
    caching proxy software with version
  • %t
    local time
  • %T
    UTC time
  • %U
    URL without password
  • %u
    URL with password
  • %W
    Extended error page data URL-encoded for mailto links.
  • %w
    cachemgr email address
  • %x
    Application-level error name or identifier (e.g.,
    X509_V_ERR_UNABLE_TO_GET_CRL). Currently only supported for
    SSL certificate validation errors. See also: system-level error
    code/detail (%e/%E) and application-level error detail (%D).
  • %z
    DNS server error message
  • %Z
    Message generated during the process which failed. May be
    ASCII-formatted. Use within HTML PRE tags.

🔗 Custom error pages not displayed for HTTPS

HTTPS uses HTTP CONNECT messages to relay through a proxy. Due to
browser behaviour handling these CONNECT messages (described in
https://bugzilla.mozilla.org/show_bug.cgi?id=479880) any custom
error page produced by the proxy is ignored and a generic browser page
displayed instead.

Usually this browser page mentions connection faulure or other such
irrelevant details.

In fact any response other than 200 OK is completely dropped by the
browser and the same browser template page displayed. This can lead to
some very weird authentication problems when using HTTPS through an
authenticated proxy as well for authentication schemes where the 407
message body has relevance.

Categories: Feature

Navigation: Site Search,
Site Pages,
Categories, 🔼 go up

imageПосле того как мы начнём в боевом режиме использовать прокси-сервер Squid3, возможно одна из первых вещей, которые захочется сделать – это кастомизация веб-страниц, возвращаемых прокси-сервером при разного рода ошибках доступа к запрашиваемым веб-ресурсам. В целом дизайн страниц ошибок в конфигурации по умолчанию в Squid3 на мой взгляд намного приятней, чем в том же Squid2 и поэтому, по большому счету, необходимости в какой-то сильной кастомизации нет. И самое простое здесь, что мы можем сделать, для того чтобы как-то приблизить этот дизайн к корпоративному – заменить логотип Squid, используемый на всех таких страницах на эмблему компании. Давайте рассмотрим эту нехитрую процедуру.

Для начала создаём новый логотип в формате png. При необходимости очищаем фон изображения с помощью онлайн-сервиса Photo editor online как описано например в заметке — Как сделать прозрачный фон у картинки.

Передаём получившийся графический файл логотипа, например это будет файл SBS-Logo.png с компьютера под управлением Windows на Linux-сервер (в нашем примере KOM-AD01-GW10). Сделать это можно например по протоколу SSH (ранее мы уже запустили службу сервера OpenSSH на KOM-AD01-GW10) с помощью утилиты WinSCP или PSCP. Передадим файл сначала в домашний каталог пользователя /home/user/ (или ~ для краткости):

C:ToolsPuTTypscp -scp C:TempMy-Logo.png user@KOM-AD01-GW10:~/My-Logo.png

Указанный файл логотипа нам нужно сделать доступным по протоколу HTTP всем пользователям локальной сети без дополнительной аутентификации. Для этого можно, например, из домашнего каталога /home/user/ переместить файл лого в в каталог /var/www/html/ (корневой каталог веб-сервера Apache2, который доступен нам после его установки в предыдущей части):

sudo mv ~/My-Logo.png  /var/www/html/My-Logo.png

После этого правим ссылку на файл лого в настроечном файле каскадных стилей /etc/squid3/errorpage.css — в секции titles изменяем значение параметра background:

/* Page displayed title area */
#titles {
        margin-left: 15px;
        padding: 10px;
        padding-left: 100px;
        /* background: url('http://www.squid-cache.org/Artwork/SN.png') no-repeat left; */
        background: url('http://KOM-AD01-GW10.holding.com/My-Logo.png') no-repeat left;
}

Перезагружаем Squid:

sudo service squid3 reload

Проверяем результат, например набрав заведомо неверный URL

image

Помимо этого в основном конфигурационном файле Squid3 /etc/squid3/squid.conf есть ряд параметров, которые могут видоизменять формат выводимых данных на страница ошибок. Найти эти параметры можно в разделе ERROR PAGE OPTIONS:

error_directory
error_default_language
err_page_stylesheet
email_err_data
deny_info

Каждый из параметров имеет комментарии объясняющие возможные значения принимаемые в этих параметрах. На приведённом скриншоте страница ошибки принимает вид согласно параметрам настроенным в конфигурационном файле squid.conf, который мы рассмотрели в одной их прошлых заметок.

***

Предыдущие части цикла заметок:

Часть 1. Установка ОС на ВМ Hyper-V Gen2
Часть 2. Настройка диска для кэша Squid
Часть 3. Конфигурация DNS , NTP и установка Squid
Часть 4. Конфигурация Kerberos и NTLM
Часть 5. Конфигурация Squid 3
Часть 6. Настройка Proxy Auto Configuration (WPAD)

Следующие части цикла заметок:

Часть 8. Конфигурация SqStat
Часть 9. Конфигурация LightSquid
Часть 10. Отключаем IPv6

If you do not have a configured error_directory as mentioned, squid -v will report your version of squids compile time options.

The following options will impact the path to the error templates:

  --prefix=PREFIX         install architecture-independent files in PREFIX
                      [/usr/local/squid]
  --datarootdir=DIR       read-only arch.-independent data root [PREFIX/share]
  --datadir=DIR           read-only architecture-independent data [DATAROOTDIR]

The following will impact which error templates are rendered:

  --disable-translation   Prevent Squid generating localized error page
  --disable-auto-locale   This prevents Squid providing localized error pages

So you end up with PREFIX/DATADIR/errors/templates as the default or PREFIX/DATADIR/errors/$locale/

Locale can be based on the clients request if using a recent version of Squid or yours was compiled with --enable-auto-locale for older versions (3.1)

The error_default_language config option can be involved as well.

Then the templates directory is the fallback.

I think this holds true for squid 3.x. Not so sure about 2.x

Contents

  1. Squid is ugly

    1. Configuration
    2. Custom pages

Squid is ugly

Squid error pages are ugly, here’s how you can change it.

Configuration

This assumes you already have a squid proxy installation which is up and running.

Squid is serving static pages on errors, denies or on other problematic situations. All those pages can be found in /usr/share/squid/errors/. The pages are stored in folders with language names. Those folders are actually the squid translated pages.

We can change the language squid serves pages by editing /etc/squid/squid.conf configuration file. Find the error_directory directive and change it’s value to the path where your language files are stored.

error_directory /usr/share/squid/errors/Romanian

Ok, but this doesn’t make Squid error pages prettier! To get this issue fixed you can edit every page inside the error pages directory to suit your needs, or, you can use sed!

Custom pages

Make a copy of your language folder first.

mkdir /etc/squid/pages/
cp -r /usr/share/squid/errors/Romanian /etc/squid/pages/

Now cause it is HTML the pages inside that folder are written in, we can use CSS to prettify those. Here’s a simple sed usage to quickly search and replace the default squid error pages CSS tag with some custom CSS:

sed -i 's/<STYLE type="text/css"><!--BODY{background-color:#ffffff;font-family:verdana,sans-serif}PRE{font-family:sans-serif}--></STYLE>/<STYLE type="text/css"><!--BODY{width:70%; margin: 50px auto;font-family:Georgia,serif; color: #4a4a4a}a:link{color:#cc0000}a:visited{color:#666}--></STYLE>/g' *

Now edit again your squid config file and point error_directory to the new location of your error pages. Reload squid:

invoke-rc.d squid reload

Point a browser which uses you squid proxy to some impossible domain name. The resulted error pages are amazingly beautiful! http://img261.imageshack.us/img261/4757/screenshoteroareurlulce.png

You can go further and customize your pages in any way you want. Good luck!

I have the following ACLs here at my squid.conf with a custom «error page» file called ERR_TJS, located at «/usr/share/squid/errors/English»:

acl tjs_sites url_regex "/etc/squid/sites_regex.acl"
acl tjs_domains dstdomain "/etc/squid/domains.acl"
http_access deny tjs_sites
http_access deny tjs_domains
deny_info ERR_TJS tjs_sites
deny_info ERR_TJS tjs_domains

Specially for the ACL file «/etc/squid/domains.acl», I have the following domains:

flyordie.com
www.flyordie.com
king.com
www.king.com
miniclip.com
www.miniclip.com
kongregate.com
www.kongregate.com
clashroyale.com
www.clashroyale.com
facebook.com
www.facebook.com
instagram.com
www.instagram.com
snapchat.com
www.snapchat.com

The problem is that when a HTTPS request is performed to Squid, instead of giving the custom error page for «https://www.facebook.com», for example, is showing a generic error page sent by the browser, like this one from Mozilla Firefox:

The proxy server is refusing connections

Firefox is configured to use a proxy server that is refusing connections.

Check the proxy settings to make sure that they are correct.
Contact your network administrator to make sure the proxy server is working.

I found this information at Squid Documentation:

Custom error pages not displayed for HTTPS

HTTPS uses HTTP CONNECT messages to relay through a proxy. Due to browser behaviour handling these CONNECT messages (described in https://bugzilla.mozilla.org/show_bug.cgi?id=479880) any custom error page produced by the proxy is ignored and a generic browser page displayed instead.

Usually this browser page mentions connection faulure or other such irrelevant details.

In fact any response other than 200 OK is completely dropped by the browser and the same browser template page displayed. This can lead to some very weird authentication problems when using HTTPS through an authenticated proxy as well for authentication schemes where the 407 message body has relevance.

I heard that with Squid, you can intercept some «states» from HTTP/HTTPS connections, like handling these CONNECT messages..

My questions are: is there any way to apply a custom deny_info like this one that I have for HTTPS requests, maybe manipulating these CONNECT messages, or via any other method? And how can I achieve this (with some example, please) ?

Понравилась статья? Поделить с друзьями:
  • Squid ошибка 1067
  • Squid коды ошибок
  • Sql ошибка 15025
  • Sql ошибка 258
  • Sql ошибка 209