proxy
12 TopicsProxy Protocol v2 Initiator
Problem this snippet solves: Proxy Protocol v1 related articles have already been posted on DevCentral, but there is no v2 support iRule code available. A customer wanted to support Proxy Protocol v2, so I wrote an iRule code for supporting v2. Proxy protocol for the BIG-IP (f5.com) How to use this snippet: Back-end server must handle Proxy header prior data exchange. Code : when CLIENT_ACCEPTED { # DEBUG On/Off set DEBUG 0 set v2_proxy_header "0d0a0d0a000d0a515549540a" # v2 version and command : 0x21 - version 2 & PROXY command set v2_ver_command "21" # v2 address family and transport protocol : 0x11 - AF_INET (IPv4) & TCP protocol set v2_af_tp "11" # v2 Address Size : 0x000C - 12 bytes for IPv4 + TCP set v2_address_length "000c" # Get TCP port - 2 byte hexadecimal format set src_port [format "%04x" [TCP::client_port]] set dst_port [format "%04x" [TCP::local_port]] # Get Src Address and convert to 4 byte hexadecimal format foreach val [split [IP::client_addr] "."] { append src_addr [format "%02x" $val] } # Get Dst Address and convert to 4 byte hexadecimal format foreach val [split [IP::local_addr] "."] { append dst_addr [format "%02x" $val] } # Build proxy v2 data set proxy_data [binary format H* "${v2_proxy_header}${v2_ver_command}${v2_af_tp}${v2_address_length}${src_addr}${dst_addr}${src_port}${dst_port}"] if { $DEBUG } { binary scan $proxy_data H* proxy_dump log local0. "[IP::client_addr]:[TCP::client_port]_[IP::local_addr]:[TCP::local_port] - proxy_data dump : $proxy_dump" } } when SERVER_CONNECTED { TCP::respond $proxy_data }250Views2likes0CommentsProxy Protocol Receiver
Problem this snippet solves: iRule for BIG-IP to receive PROXY protocol (v1 and v2) header in TCP Payload and remove it before forwarding remaining TCP Payload to server side pool member. How to use this snippet: Enable iRule on virtual server where upstream proxy will be sending PROXY header. Testing done using proxied IPv6 and IPv4 HTTP connections from HAProxy using Proxy Protocol v1 and v2. Use of client or server SSL profiles slated for testing and validation since ELB promotes use of Proxy Protocol as a solution for customers that don't want to have ELB terminate HTTPS traffic but do want servers to see original IP addresses. Code : #PROXY Protocol Receiver iRule # c.jenison at f5.com (Chad Jenison) # v2.0 - Added support for PROXY Protocol v2, control for v1,v2 or lack of proxy via static:: variables set in RULE_INIT # v2.1 - Fix for skipping bytes in v2 code when RULE_INIT { set static::allowProxyV1 0 set static::allowProxyV2 1 set static::allowNoProxy 0 } when CLIENT_ACCEPTED { TCP::collect } when CLIENT_DATA { binary scan [TCP::payload 12] H* v2_protocol_sig if {$static::allowProxyV1 && [TCP::payload 0 5] eq "PROXY"} { set proxy_string [TCP::payload] set proxy_string_length [expr {[string first "\r" [TCP::payload]] + 2}] scan $proxy_string {PROXY TCP%s%s%s%s%s} tcpver srcaddr dstaddr srcport dstport log "Proxy Protocol v1 conn from [IP::client_addr]:[TCP::client_port] for an IPv$tcpver stream from Src: $srcaddr:$srcport to Dst: $dstaddr:$dstport" TCP::payload replace 0 $proxy_string_length "" } elseif {$static::allowProxyV2 && $v2_protocol_sig eq "0d0a0d0a000d0a515549540a"}{ binary scan [TCP::payload] @12H* v2_proxyheaderremainder binary scan [TCP::payload] @12H2H* v2_verCommand v2_remainder if {$v2_verCommand == 21}{ binary scan [TCP::payload] @13H2 v2_addressFamilyTransportProtocol if {$v2_addressFamilyTransportProtocol == 11} { binary scan [TCP::payload] @16ccccccccSS v2_sourceAddress1 v2_sourceAddress2 v2_sourceAddress3 v2_sourceAddress4 v2_destAddress1 v2_destAddress2 v2_destAddress3 v2_destAddress4 v2_sourcePort1 v2_destPort1 set v2_sourceAddress "[expr {$v2_sourceAddress1 & 0xff}].[expr {$v2_sourceAddress2 & 0xff}].[expr {$v2_sourceAddress3 & 0xff}].[expr {$v2_sourceAddress4 & 0xff}]" set v2_destAddress "[expr {$v2_destAddress1 & 0xff}].[expr {$v2_destAddress2 & 0xff}].[expr {$v2_destAddress3 & 0xff}].[expr {$v2_destAddress4 & 0xff}]" set v2_sourcePort [expr {$v2_sourcePort1 & 0xffff}] set v2_destPort [expr {$v2_destPort1 & 0xffff}] log "Proxy Protocol v2 conn from [IP::client_addr]:[TCP::client_port] for an IPv4 Stream from Src: $v2_sourceAddress:$v2_sourcePort to Dst: $v2_destAddress:$v2_destPort" binary scan [TCP::payload] @14S address_size set skip_bytes [expr 16 + $address_size] TCP::payload replace 0 $skip_bytes "" } elseif {$v2_addressFamilyTransportProtocol == 21} { binary scan [TCP::payload] @16H4H4H4H4H4H4H4H4 v2_v6sourceAddress1 v2_v6sourceAddress2 v2_v6sourceAddress3 v2_v6sourceAddress4 v2_v6sourceAddress5 v2_v6sourceAddress6 v2_v6sourceAddress7 v2_v6sourceAddress8 binary scan [TCP::payload] @32H4H4H4H4H4H4H4H4 v2_v6destAddress1 v2_v6destAddress2 v2_v6destAddress3 v2_v6destAddress4 v2_v6destAddress5 v2_v6destAddress6 v2_v6destAddress7 v2_v6destAddress8 binary scan [TCP::payload] @48SS v2_v6sourcePort1 v2_v6destPort1 set v2_v6sourcePort [expr {$v2_v6sourcePort1 & 0xffff}] set v2_v6destPort [expr {$v2_v6destPort1 & 0xffff}] set v2_v6sourceAddress "$v2_v6sourceAddress1:$v2_v6sourceAddress2:$v2_v6sourceAddress3:$v2_v6sourceAddress4:$v2_v6sourceAddress5:$v2_v6sourceAddress6:$v2_v6sourceAddress7:$v2_v6sourceAddress8" set v2_v6destAddress "$v2_v6destAddress1:$v2_v6destAddress2:$v2_v6destAddress3:$v2_v6destAddress4:$v2_v6destAddress5:$v2_v6destAddress6:$v2_v6destAddress7:$v2_v6destAddress8" log "Proxy Protocol v2 conn from from [IP::client_addr]:[TCP::client_port] for an IPv6 Stream from Src: $v2_v6sourceAddress:$v2_v6sourcePort to Dst: $v2_v6destAddress:$v2_v6destPort" binary scan [TCP::payload] @14S address_size set skip_bytes [expr 16 + $address_size] TCP::payload replace 0 $skip_bytes "" } else { log "v2_proxy conn from [IP::client_addr]:[TCP::client_port] - possible unknown/malformed transportProtocol or addressFamily" reject } } elseif {$v2_verCommand == 20}{ log "Proxy Protocol v2 and LOCAL command from [IP::client_addr]:[TCP::client_port]; skipping" binary scan [TCP::payload] @14S address_size set skip_bytes [expr 16 + $address_size] TCP::payload replace 0 $skip_bytes "" binary scan [TCP::payload] H* local_remainder } else { log "Proxy Protocol Protocol Signature Detected from [IP::client_addr]:[TCP::client_port] but protocol version and command not legal; connection reset" reject } } elseif {$static::allowNoProxy} { log "Connection from [IP::client_addr]:[TCP::client_port] allowed despite lack of PROXY protocol header" } else { reject log "Connection rejected from [IP::client_addr]:[TCP::client_port] due to lack of PROXY protocol header" } TCP::release } Tested this on version: 12.05.1KViews0likes9CommentsProxyPass v10/v11
Problem this snippet solves: iRule to replace the functionality of Apache Webserver ProxyPass and ProxyPassReverse functions. Allows you to do hostname and path name modifications as HTTP traffic passes through the LTM. This optimized version requires TMOS v10 or higher. If you are using APM for authentication on the virtual server, please use the ProxyPass_for_use_with_APM iRule instead. (Full documentation follows the iRule.) For use with TMOS v9, see ProxyPass v8.2 Note: In 10.1+ you can use an internal data group to store the ProxyPass configuration. Ignore the comments to the contrary in the instructions as these were for pre-10.1 releases. Please post questions or fixes for this iRule in the iRules forum to get the fastest response. Thanks Aaron. Introduction Sometimes it is desirable to have a different look and feel to your website on the outside than you have in the inside. You may want www.company.com/usa/ to internally go to the server usa.company.com. You may want support.company.com to go internally to abc123.company.com/web/support. This can create a few issues - sometimes the web server expects to see a certain hostname (i.e. for name-based virtual hosting) or will use the internal hostname and/or path when sending a redirect to the clients. These problems can be overcome with the Apache webserver using the ProxyPass module which can translate the URL on the way into the server, and the ProxyPassReverse module which can un-translate header fields such as Location in the case of a redirect. Now you can accomplish this with an iRule. The ProxyPass iRule translates incoming requests in a flexible manner and untranslates the Location, Content-Location, and/or URI headers in the response back to the client. ProxyPass also rewrites the domain and path in cookies set by the server. Page Content Modification In addition, this rule will perform basic page modification as needed (this feature is disabled by default but can be enabled in the RULE_INIT event). Using the example from the introduction, if the page content contains a link to http://abc123.company.com/web/support/viewticket.html, the iRule will modify that to be http://support.company.com/viewticket.html. Here are some examples: < a href=http://www.domain.com/path/file.html> will be modified assuming the incoming request was matched by the ProxyPass iRule and the inside hostname was www.domain.com and the inside path was /path. < a href="page2.html"> will not need to be modified as this is a URL already relative to the path. Even relative URLs such as < a href="../page2.html"> will work as long as it does not try to go above the top-level directory defined by the ProxyPass rules. You must have a stream profile defined on any virtual servers the rule is applied to in order to enable the page modification feature. Virtual Server The first step to using the ProxyPass iRule is to define the rule on your BIG-IP and associate it with one or more Virtual Servers. Note that each virtual server MUST have an HTTP profile defined (doesn't matter which one). I also highly recommend applying a OneConnect profile, especially if you will be choosing pools with ProxyPass. It also must have a stream profile associated with it if you want to uncomment the page modification code. The rule will work on HTTP sites as well as HTTPS sites where the SSL is terminated on the BIG-IP (i.e. a client-side SSL profile is defined). Data Groups You can apply the ProxyPass rule to any virtual server that you want to do translations on. But just applying the rule will have no effect unless you define the translations you want done. This is done by defining specific Data Groups. The ProxyPass iRule uses Data Groups which are created and managed by going to Local Traffic / Virtual Servers / iRules on the left menu bar in the BIG-IP GUI. Then choose the "Data Group List" tab at the top of the screen. Here you can create the data groups used by this rule. For 10.0.x, the data groups must be External, type "String", and Read-only. For 10.1 and higher, the data group can be internal or external with name=value pairings. In order to use this rule on a virtual server you must apply the rule to the virtual server and create a data group named ProxyPassXYZ where "XYZ" needs to be the name of the virtual server. If both of these conditions are not met then the rule will not work for that virtual server. ProxyPassXYZ Data Groups If your virtual server is named XYZ and has the ProxyPass iRule associated with it, it will look for a data group named ProxyPassXYZ. Assuming that class is found, for each new HTTP request, the rule will find the one row that matches the hostname/path used in the request. For example, the data group may contain 4 entries (each line below is one string in the data group): "www.usa.company.com/support" := "support.company-internal.com:8080/usa", "www.usa.company.com/" := "www.company-internal.com:8080/usa", "www.japan.company.com/" := "www.company-internal.com:8080/japan", "/" := "www.company-internal.com:8080/others", A request need not match any entries - if no entries match then the iRule will have no effect. But each request will only match at most one entry and that will be the entry with the most specific left-hand-side. Entries with hostnames specified on the left-hand-side will be matched before entries without hostnames. If multiple entries match then the entry with the longest path name on the left-hand-side will be used. The example above lists entries from most-specific to least-specific, just as the rule will process them, but in your actual data group the order of the entries does not matter. In the example above, requests to http://www.usa.company.com/support will match the first entry and have the host header changed to "support.company-internal.com:8080" and the URI will be rewritten so that the string /support at the beginning of the URI will be changed to /usa. Furthermore, requests to http://www.usa.company.com/ will match the second entry as long as the URI does not begin with "/support" in which case it would match the first entry. In that case the Host header will be changed to "www.company-internal.com:8080" and whatever URI the client sends in will be prepended with "/usa". Likewise all requests to http://www.japan.company.com/ will match the third entry and have the Host header changed to "www.company-internal.com:8080" and the URIs would be prepended with "/japan". Finally, all other requests that hit this example virtual server would match the least-specific rule which is simply "/" -- all URIs begin with "/" and thus all requests will match the fourth entry if they did not match any others. Remember that a catch-all entry is not required, but in this example we want to prepend the URI of all other requests with "/others". Note that the ProxyPass iRule does not actually alter the destination of the requests by default. In the examples above all of the requests would go to the default pool regardless of the entries they match. The hostnames and ports specified in the right-hand entry is only used to modify the Host header. To alter the destination pool see the next section. Dynamic Pool Selection You may also specify an alternate pool as a second item in the right-hand value of the entry. This is optional any items in the list without a pool name will just use the default pool associated with the virtual server. For example: "/support" := "support.company.com/ SupportPool", "/downloads" := "downloads.company.com/ DownloadPool", If the pool name is not valid the user will get an error and you should see an error message in /var/log/ltm. Dynamic SNAT You can optionally define a ProxyPassSNATs data group. This will allow you to use different SNAT IP based on which pool you send traffic to. The ProxyPassSNATs data group is shared by all virtual servers but will only have an effect if the selected pool is listed in the data group. The format of this data group (internal string type) is: Pool1 W.X.Y.Z Pool2 automap Dynamic ServerSSL Profiles You can optionally define a ProxyPassSSLProfiles data group and apply a generic serverssl profile to the virtual server. This will allow you to use different serverssl profiles based on which pool you send traffic to. The ProxyPassSSLProfiles data group is shared by all virtual servers but will only have an effect if the selected pool is listed in the data group and a generic serverssl is applied to the virtual server. The format of this data group (internal string type) is: Pool1 ServerSSLProfile1 Pool2 ServerSSLProfile2 Regular Expressions New in v10: you may also use regular expressions and backreferences when building your rule set. "/" := "=www.company.com/(.*?)/=$1.company.com/=", As you see, instead of a regular server-side entry, we have "=regex=replace=". Basically, in order for the regex to be run, the left-hand side must match the client host/path (just "/" in this case, which will always match unless something more specific matches). Once this happens, the client host and URI are combined into a form similar to www.domain.com/path and the regular expression is run a against it. If the regular expression does not match, ProxyPass does not alter the request. If it does match, the clientside path becomes the match string and the serverside path becomes the replace string. Within this replace string you can use $1 through $9 as back-references to grouped items in the original regular expression. So, the example above, entry is equivalent to all of these entries: "www.company.com/sales" := "sales.company.com/", "www.company.com/support" := "support.company.com/", "www.company.com/employment" := "employment.company.com/", Debugging You can debug your ProxyPass rules by setting the static::ProxyPassDebug variable at the top of the rule to 1 (or 2 for more verbose debugging). Once you do this you can SSH to the BIG-IP and run the command "tail -f /var/log/ltm" to see what ProxyPass is doing to your requests. Code : # ProxyPass iRule, Version 10.9 # Nov 26 2012. Date # THIS VERSION REQUIRES TMOS v10 or higher. Use ProxyPass v8.2 for TMOS 9.x. # This version does not work with APM-enabled virtual servers, please # download ProxyPass 10.2APM for this use case. # Created by Kirk Bauer # https://devcentral.f5.com/s/wiki/default.aspx/iRules/ProxyPassV10.html # (please see end of iRule for additional credits) # Purpose: # iRule to replace the functionality of Apache Webserver ProxyPass and # ProxyPassReverse functions. It allows you to perform host name and path name # modifications as HTTP traffic passes through the LTM. In other words, you # can have different hostnames and directory names on the client side as you # do on the server side and ProxyPass handles the necessary translations. # NOTE: You should not need to modify this iRule in any way except the settings # in the RULE_INIT event. Just apply the iRule to the virtual server and # define the appropriate Data Group and you are done. If you do make any # changes to this iRule, please send your changes and reasons to me so that # I may understand how ProxyPass is being used and possibly incorporate your # changes into the core release. # Configuration Requirements # 1) The ProxyPass iRule needs to be applied to an HTTP virtual server or # an HTTPS virtual server with a clientssl profile applied to it. # 2) A data group (LTM -> iRules -> Data Groups tab) must be defined with # the name "ProxyPassVIRTUAL" where VIRTUAL is the name of the virtual server # (case-sensitive!). See below for the format of this data group (class). # For 10.0.x, you must use an EXTERNAL data group. # 3) You must define a default pool on the virtual server unless you specify # a pool in every entry in the data group. # 4) If you are using ProxyPass to select alternate pools, you must define # a OneConnect profile in most cases! # 5) ProxyPass does not rewrite links embedded within pages by default, just # headers. If you want to change this, edit the $static::RewriteResponsePayload variable in RULE_INIT # and apply the default stream profile to the virtual server. # Data Group Information # For 10.0.x, you must define an external data group (type=String, read-only) which loads # from a file on your BIG-IP. For 10.1 and higher you can use an internal string data group with name=value pairings. # The format of the file is as follows: # "clientside" := "serverside", # or # "clientside" := "serverside poolname", # The clientside and serverside fields must contain a URI (at least a "/") and # may also contain a hostname. Here are some examples: # "/clientdir" := "/serverdir", # "www.host.com/clientdir" := "internal.company.com/serverdir", # "www.host.com/" := "internal.company.com/serverdir/", # Notes: # 1) You can optionally define a ProxyPassSNATs data group to SNAT based # on the pool selected. # 2) You can optionally define a ProxyPassSSLProfiles data group to select # a serverssl profile based on the pool selected. # 3) You can also use regular expressions which is documented on DevCentral. when RULE_INIT { # Enable to debug ProxyPass translations via log messages in /var/log/ltm # (2 = verbose, 1 = essential, 0 = none) set static::ProxyPassDebug 0 # Enable to rewrite page content (try a setting of 1 first) # (2 = attempt to rewrite host/path and just /path, 1 = attempt to rewrite host/path) set static::RewriteResponsePayload 0 } when CLIENT_ACCEPTED { # Get the default pool name. This is used later to explicitly select # the default pool for requests which don't have a pool specified in # the class. set default_pool [LB::server pool] # The name of the Data Group (aka class) we are going to use. # Parse just the virtual server name by stripping off the folders (if present) set clname "ProxyPass[URI::basename [virtual name]]" if { $static::ProxyPassDebug > 1 } { log local0. "[virtual name]: [IP::client_addr]:[TCP::client_port] -> [IP::local_addr]:[TCP::local_port]" } } when HTTP_REQUEST { # "bypass" tracks whether or not we made any changes inbound so we # can skip changes on the outbound traffic for greater efficiency. set bypass 1 # Initialize other local variables used in this rule set orig_uri "[HTTP::uri]" set orig_host "[HTTP::host]" set log_prefix "VS=[virtual name], Host=$orig_host, URI=$orig_uri" set clientside "" set serverside "" set newpool "" set ppass "" if {! [class exists $clname]} { log local0. "$log_prefix: Data group $clname not found, exiting." pool $default_pool return } else { set ppass [class match -element "$orig_host$orig_uri" starts_with $clname] if {$ppass eq ""} { # Did not find with hostname, look for just path set ppass [class match -element "$orig_uri" starts_with $clname] } if {$ppass eq ""} { # No entries found if { $static::ProxyPassDebug > 0 } { log local0. "$log_prefix: No rule found, using default pool $default_pool and exiting" } pool $default_pool return } } # Store each entry in the data group line into a local variable set clientside [getfield $ppass " " 1] set serverside [string trimleft [getfield $ppass " " 2 ] "{" ] set newpool [string trimright [getfield $ppass " " 3 ] "}" ] # If serverside is in the form =match=replace=, apply regex if {$serverside starts_with "="} { set regex [getfield $serverside "=" 2] set rewrite [getfield $serverside "=" 3] if {[regexp -nocase $regex "$orig_host$orig_uri" 0 1 2 3 4 5 6 7 8 9]}{ # The clientside becomes the matched string and the serverside the substitution set clientside $0 set serverside [eval set X $rewrite] } else { pool $default_pool return } } if {$clientside starts_with "/"} { # No virtual hostname specified, so use the Host header instead set host_clientside $orig_host set path_clientside $clientside } else { # Virtual host specified in entry, split the host and path set host_clientside [getfield $clientside "/" 1] set path_clientside [substr $clientside [string length $host_clientside]] } # At this point $host_clientside is the client hostname, and $path_clientside # is the client-side path as specified in the data group set host_serverside [getfield $serverside "/" 1] set path_serverside [substr $serverside [string length $host_serverside]] if {$host_serverside eq ""} { set host_serverside $host_clientside } # At this point $host_serverside is the server hostname, and $path_serverside # is the server-side path as specified in the data group # In order for directory redirects to work properly we have to be careful with slashes if {$path_clientside equals "/"} { # Make sure serverside path ends with / if clientside path is "/" if {!($path_serverside ends_with "/")} { append path_serverside "/" } } else { # Otherwise, neither can end in a / (unless serverside path is just "/") if {!($path_serverside equals "/")} { if {$path_serverside ends_with "/"} { set path_serverside [string trimright $path_serverside "/"] } if {$path_clientside ends_with "/"} { set path_clientside [string trimright $path_clientside "/"] } } } if { $static::ProxyPassDebug } { log local0. "$log_prefix: Found Rule, Client Host=$host_clientside, Client Path=$path_clientside, Server Host=$host_serverside, Server Path=$path_serverside" } # If you go to http://www.domain.com/dir, and /dir is a directory, the web # server will redirect you to http://www.domain.com/dir/. The problem is, with ProxyPass, if the client-side # path is http://www.domain.com/dir, but the server-side path is http://www.domain.com/, the server will NOT # redirect the client (it isn't going to redirect you to http://www.domain.com//!). Here is the problem with # that. If there is an image referenced on the page, say logo.jpg, the client doesn't realize /dir is a directory # and as such it will try to load http://www.domain.com/logo.jpg and not http://www.domain.com/dir/logo.jpg. So # ProxyPass has to handle the redirect in this case. This only really matters if the server-side path is "/", # but since we have the code here we might as well offload all of the redirects that we can (that is whenever # the client path is exactly the client path specified in the data group but not "/"). if {$orig_uri eq $path_clientside} { if {([string index $path_clientside end] ne "/") and not ($path_clientside contains ".") } { set is_https 0 if {[PROFILE::exists clientssl] == 1} { set is_https 1 } # Assumption here is that the browser is hitting http://host/path which is a virtual path and we need to do the redirect for them if {$is_https == 1} { HTTP::redirect "https://$orig_host$orig_uri/" if { $static::ProxyPassDebug } { log local0. "$log_prefix: Redirecting to https://$orig_host$orig_uri/" } } else { HTTP::redirect "http://$orig_host$orig_uri/" if { $static::ProxyPassDebug } { log local0. "$log_prefix: Redirecting to http://$orig_host$orig_uri/" } } return } } if {$host_clientside eq $orig_host} { if {$orig_uri starts_with $path_clientside} { set bypass 0 # Take care of pool selection if {$newpool eq ""} { pool $default_pool if { $static::ProxyPassDebug > 1 } { log local0. "$log_prefix: Using default pool $default_pool" } set newpool $default_pool } else { pool $newpool if { $static::ProxyPassDebug > 0 } { log local0. "$log_prefix: Using parsed pool $newpool (make sure you have OneConnect enabled)" } } } } # If we did not match anything, skip the rest of this event if {$bypass} { return } # The following code will look up SNAT addresses from # the data group "ProxyPassSNATs" and apply them. # # The format of the entries in this list is as follows: # # # # All entries are separated by spaces, and both items # are required. set class_exists_cmd "class exists ProxyPassSNATs" if {! [eval $class_exists_cmd]} { return } set snat [findclass $newpool ProxyPassSNATs " "] if {$snat eq ""} { # No snat found, skip rest of this event return } if { $static::ProxyPassDebug > 0 } { log local0. "$log_prefix: SNAT address $snat assigned for pool $newpool" } snat $snat } when HTTP_REQUEST_SEND { # If we didn't match anything, skip the rest of this event if {$bypass} { return } # The following code does the actual rewrite on its way TO # the backend server. It replaces the URI with the newly # constructed one and masks the "Host" header with the FQDN # the backend pool server wants to see. # # If a new pool or custom SNAT are to be applied, these are # done here as well. If a SNAT is used, an X-Forwarded-For # header is attached to send the original requesting IP # through to the server. if {$host_clientside eq $orig_host} { if {$orig_uri starts_with $path_clientside} { if { $static::ProxyPassDebug > 1 } { log local0. "$log_prefix: New Host=$host_serverside, New Path=$path_serverside[substr $orig_uri [string length $path_clientside]]" } clientside { # Rewrite the URI HTTP::uri $path_serverside[substr $orig_uri [string length $path_clientside]] # Rewrite the Host header HTTP::header replace Host $host_serverside # Now alter the Referer header if necessary if { [HTTP::header exists "Referer"] } { set protocol [URI::protocol [HTTP::header Referer]] if {$protocol ne ""} { set client_path [findstr [HTTP::header "Referer"] $host_clientside [string length $host_clientside]] if {$client_path starts_with $path_clientside} { if { $static::ProxyPassDebug > 1 } { log local0. "$log_prefix: Changing Referer header: [HTTP::header Referer] to $protocol://$host_serverside$path_serverside[substr $client_path [string length $path_clientside]]" } HTTP::header replace "Referer" "$protocol://$host_serverside$path_serverside[substr $client_path [string length $path_clientside]]" } } } } } } # If we're rewriting the response content, prevent the server from using #compression in its response by removing the Accept-Encoding header #from the request. LTM does not decompress response content before #applying the stream profile. This header is only removed if we're #rewriting response content. clientside { if { $static::RewriteResponsePayload } { if { [HTTP::header exists "Accept-Encoding"] } { HTTP::header remove "Accept-Encoding" if { $static::ProxyPassDebug > 1} { log local0. "$log_prefix: Removed Accept-Encoding header" } } } HTTP::header insert "X-Forwarded-For" "[IP::remote_addr]" } } when HTTP_RESPONSE { if { $static::ProxyPassDebug > 1 } { log local0. "$log_prefix: [HTTP::status] response from [LB::server]" } if {$bypass} { # No modification is necessary if we didn't change anything inbound so disable the stream filter if it was enabled # Check if we're rewriting the response if {$static::RewriteResponsePayload} { if { $static::ProxyPassDebug > 1 } { log local0. "$log_prefix: Rewriting response content enabled, but disabled on this response." } # Need to explicity disable the stream filter if it's not needed for this response # Hide the command from the iRule parser so it won't generate a validation error #when not using a stream profile set stream_disable_cmd "STREAM::disable" # Execute the STREAM::disable command. Use catch to handle any errors. Save the result to $result if { [catch {eval $stream_disable_cmd} result] } { # There was an error trying to disable the stream profile. log local0. "$log_prefix: Error disabling stream filter ($result). If you enable static::RewriteResponsePayload, then you should add a stream profile to the VIP. Else, set static::RewriteResponsePayload to 0 in this iRule." } } # Exit from this event. return } # Check if we're rewriting the response if {$static::RewriteResponsePayload} { # Configure and enable the stream filter to rewrite the response payload # Hide the command from the iRule parser so it won't generate a validation error #when not using a stream profile if {$static::RewriteResponsePayload > 1} { set stream_expression_cmd "STREAM::expression \"@$host_serverside$path_serverside@$host_clientside$path_clientside@ @$path_serverside@$path_clientside@\"" } else { set stream_expression_cmd "STREAM::expression \"@$host_serverside$path_serverside@$host_clientside$path_clientside@\"" } set stream_enable_cmd "STREAM::enable" if { $static::ProxyPassDebug > 1 } { log local0. "$log_prefix: \$stream_expression_cmd: $stream_expression_cmd, \$stream_enable_cmd: $stream_enable_cmd" } # Execute the STREAM::expression command. Use catch to handle any errors. Save the result to $result if { [catch {eval $stream_expression_cmd} result] } { # There was an error trying to set the stream expression. log local0. "$log_prefix: Error setting stream expression ($result). If you enable static::RewriteResponsePayload, then you should add a stream profile to the VIP. Else, set static::RewriteResponsePayload to 0 in this iRule." } else { # No error setting the stream expression, so try to enable the stream filter # Execute the STREAM::enable command. Use catch to handle any errors. Save the result to $result if { [catch {eval $stream_enable_cmd} result] } { # There was an error trying to enable the stream filter. log local0. "$log_prefix: error enabling stream filter ($result)" } else { if { $static::ProxyPassDebug > 1 } { log local0. "$log_prefix: Successfully configured and enabled stream filter" } } } } # Fix Location, Content-Location, and URI headers foreach header {"Location" "Content-Location" "URI"} { set protocol [URI::protocol [HTTP::header $header]] if { $static::ProxyPassDebug > 1 } { log local0. "$log_prefix: Checking $header=[HTTP::header $header], \$protocol=$protocol" } if {$protocol ne ""} { set server_path [findstr [HTTP::header $header] $host_serverside [string length $host_serverside]] if {$server_path starts_with $path_serverside} { if { $static::ProxyPassDebug } { log local0. "$log_prefix: Changing response header $header: [HTTP::header $header] with $protocol://$host_clientside$path_clientside[substr $server_path [string length $path_serverside]]" } HTTP::header replace $header $protocol://$host_clientside$path_clientside[substr $server_path [string length $path_serverside]] } } } # Rewrite any domains/paths in Set-Cookie headers if {[HTTP::header exists "Set-Cookie"]}{ array unset cookielist foreach cookievalue [HTTP::header values "Set-Cookie"] { set cookiename [getfield $cookievalue "=" 1] set namevalue "" set newcookievalue "" foreach element [split $cookievalue ";"] { set element [string trim $element] if {$namevalue equals ""} { set namevalue $element } else { if {$element contains "="} { set elementname [getfield $element "=" 1] set elementvalue [getfield $element "=" 2] if {[string tolower $elementname] eq "domain"} { set elementvalue [string trimright $elementvalue "."] if {$host_serverside ends_with $elementvalue} { if {$static::ProxyPassDebug > 1} { log local0. "$log_prefix: Modifying cookie $cookiename domain from $elementvalue to $host_clientside" } set elementvalue $host_clientside } append elementvalue "." } if {[string tolower $elementname] eq "path"} { if {$elementvalue starts_with $path_serverside} { if {$static::ProxyPassDebug > 1} { log local0. "$log_prefix: Modifying cookie $cookiename path from $elementvalue to $path_clientside[substr $elementvalue [string length $path_serverside]]" } set elementvalue $path_clientside[substr $elementvalue [string length $path_serverside]] } } append newcookievalue "; $elementname=$elementvalue" } else { append newcookievalue "; $element" } } } set cookielist($cookiename) "$namevalue$newcookievalue" } HTTP::header remove "Set-Cookie" foreach cookiename [array names cookielist] { HTTP::header insert "Set-Cookie" $cookielist($cookiename) if {$static::ProxyPassDebug > 1} { log local0. "$log_prefix: Inserting cookie: $cookielist($cookiename)" } } } } # Only uncomment this event if you need extra debugging for content rewriting. # This event can only be uncommented if the iRule is used with a stream profile. #when STREAM_MATCHED { #if { $static::ProxyPassDebug } { #log local0. "$log_prefix: Rewriting match: [STREAM::match]" #} #} # The following code will look up SSL profile rules from # the Data Group ProxyPassSSLProfiles" and apply # them. # # The format of the entries in this list is as follows: # # # # All entries are separated by spaces, and both items # are required. The virtual server also will need to # have any serverssl profile applied to it for this to work. when SERVER_CONNECTED { if {$bypass} { return } set class_exists_cmd "class exists ProxyPassSSLProfiles" if {! [eval $class_exists_cmd]} { return } set pool [LB::server pool] set profilename [findclass $pool ProxyPassSSLProfiles " "] if {$profilename eq ""} { if { [PROFILE::exists serverssl] == 1} { # Hide this command from the iRule parser (in case no serverssl profile is applied) set disable "SSL::disable serverside" catch {eval $disable} } return } if { $static::ProxyPassDebug > 0 } { log local0. "$log_prefix: ServerSSL profile $profilename assigned for pool $pool" } if { [PROFILE::exists serverssl] == 1} { # Hide these commands from the iRule parser (in case no serverssl profile is applied) set profile "SSL::profile $profilename" catch {eval $profile} set enable "SSL::enable serverside" catch {eval $enable} } else { log local0. "$log_prefix: ServerSSL profile must be defined on virtual server to enable server-side encryption!" } } # ProxyPass Release History #v10.9: Nov 26, 2012: Used URI::basename to get the virtual server name. Thanks to Opher Shachar for the suggestion. #Replaced indentations with tabs intead of spaces to save on characters #v10.8: Oct 25, 2012: Updated the class name to remove the folder(s) (if present) from the virtual server name. # This assumes the ProxyPass data group is in the same partition as the iRule. #v10.7: Oct 24, 2012: Changed array set cookielist {} to array unset cookielist as the former does not clear the array. # Thanks to rhuyerman@schubergphilis.com and Simon Kowallik for pointing out the issue and this wiki page with details: http://wiki.tcl.tk/724 #v10.6: Oct 14, 2012: Updated how the protocol is parsed from URLs in request and response headers to fix errant matches #v10.5: Feb 2, 2012: Removed extra stream profile $result reference for debug logging. #v10.4: Nov 23, 2011: Removed an extra colon in sever HTTP::header replace commands to prevent duplicate headers from being inserted #v10.3: Sep 27, 2010: Moved rewrite code to HTTP_REQUEST_SEND to work with WebAccelerator # Fixed bug with cookie rewrites when cookie value contained an "=" #v10.2: Jun 04, 2010: Can handle individual file mappings thanks to Michael Holmes from AZDOE # Also fixed bug with directory slash logic #v10.1: Oct 24, 2009: Now CMP-friendly! (NOTE: use ProxyPass v8.2 for TMOS v9.x) #v10.0: May 15, 2009: Optimized for external classes in v10 only (use v8.2 for TMOS v9.x) # Added support for regular expressions and backreferences for the translations. # v8.2: Jun 04, 2010: Fixed bug with directory slash logic # v8.1: May 15, 2009: Added internal redirects back in (removing them was a mistake) # v8.0: May 13, 2009: pulled in changes submitted by Aaron Hooley (hooleylists gmail com) # TMOS v10 support added. Cookie domain/path rewriting added. # v7.0: May 6, 2008: added optional serverssl contributed by Joel Moses # v6.0: Jan 15, 2008: Small efficiency change # v5.0: Jul 27, 2007: Added Referer header conversions # v4.0: Jul 27, 2007: Added optional debugging flag # v3.0: Jul 20, 2007: Added SNAT support contributed by Adam Auerbach # v2.0: May 28, 2007: Added internal directory redirects and optional stream profile # v1.0: Feb 20, 2007: Initial Release Tested this on version: 10.07.9KViews0likes27CommentsProxy Protocol Initiator
Problem this snippet solves: iRule Support for BIG-IP sending Proxy header to serverside pool member. (BIG-IP as Proxy Protocol Initiator) Implements v1 of PROXY protocol at: http://www.haproxy.org/download/1.5/doc/proxy-protocol.txt How to use this snippet: Add iRule to Virtual Server. Back-end server should accept Proxy header. Code : when CLIENT_ACCEPTED { set proxyheader "PROXY " if {[IP::version] eq 4} { append proxyheader "TCP4 " } else { append proxyheader "TCP6 " } append proxyheader "[IP::remote_addr] [IP::local_addr] [TCP::remote_port] [TCP::local_port]\r\n" } when SERVER_CONNECTED { TCP::respond $proxyheader } ### Alternate Optimized Version ### when CLIENT_ACCEPTED { set proxyheader "PROXY TCP[IP::version] [IP::remote_addr] [IP::local_addr] [TCP::remote_port] [TCP::local_port]\r\n" } when SERVER_CONNECTED { TCP::respond $proxyheader } Tested this on version: 11.67.2KViews0likes17CommentsLDAP Proxy
Problem this snippet solves: Summary: An LDAP proxy used send read/write requests to different pools. For anyone that is interested, I recently was posed with the problem of proxying ldap requests. The requirement was to send read and write requests to different pools. As any familiar with ldap knows, you need to send a bind request to authenticate. The following will transparently resend the bind requests to the newly selected server prior to sending the new read/write request. Other functionality could be added to this, such as more verification of the ldap fields to ensure a valid request is being made. The expr commands could be optimized with proper bracing. See the TCL expr wiki page for details Code : class ldap_writes { 6 8 10 12 } # v11 compatabile version when RULE_INIT { # Read Pool set static::readPool sun_ldap_read # Write Pool set static::writePool sun_ldap_write # Turn on debugging set static::ldap_debug 0 # A lookup table for debugging array set static::msg_types { 0 "bind request" 1 "bind response" 2 "unbind request" 3 "search request" 4 "search response" 6 "modify request" 7 "modify response" 8 "add request" 9 "add response" 10 "delete request" 11 "delete response" 12 "modifydn request" 13 "modifydn response" 14 "compare request" 15 "compare response" 16 "abandon request" 23 "extended request" 24 "extended response" } } when CLIENT_ACCEPTED { set rebind 0 set binding "" set replayop "" set writing 0 TCP::collect } when CLIENT_DATA { # Grab the current payload collected set payload [TCP::payload] # Pull the first 2 bytes. binary scan $payload H2c ber_t ber_len # The first byte is the tag signifying an LDAP message, # Always is hex 30, if that is not so reject if { $ber_t ne "30" } { reject return } # The second byte is one of two values: # a) The length of the packet minus the above # defining byte and the length byte # OR # b) an octet describing how many subsequent bytes # hold the packet length # In either case the message type (what we are after) # follows the message id field which too can be a variable # number of bytes. set len_bytes 0 if { [expr {[expr {$ber_len + 0x100} % 0x100]} & 128] > 0 } { set len_bytes [expr {[expr ($ber_len + 0x100) % 0x100]} & 127] } # How many bytes is the message id binary scan $payload x[expr {3 + $len_bytes}]c msgid_bytes # The message type is then 4 bytes + number length bytes + number of # message id bytes offset. binary scan $payload x[expr {4 + $len_bytes + $msgid_bytes}]c msgtype # msgtype - BER encoded value, bits 1-5 are the actual # type, 6 is the data type, 7-8 are the data class # Here we only care about the lower 5 bits set msgtype [expr {$msgtype & 31}] if {$static::ldap_debug and [catch { log local0. "message type is: $static::msg_types($msgtype) $msgtype" } ] } { log local0. "Bad message type: $msgtype" reject } # Each connection should start with a bind request # We'll save this packet for later rebinding when we # flip between servers if { $msgtype == 0 } { if {$static::ldap_debug} {log local0. "Bind Request with: ldap_read"} set writing 0 set rebind 0 set binding $payload LB::detach pool $static::readPool # If we come across a write request and are currently not # sending data to the write pool, detach, and set the rebind # flag so we can send the bind packet before we actually send # our write request } elseif {[class match -- $msgtype equals ldap_writes] and $writing != 1} { if {$static::ldap_debug} {log local0. "Rebinding with: ldap_write"} set rebind 1 set writing 1 set replayop $payload TCP::payload replace 0 [TCP::payload length] $binding LB::detach pool $static::writePool # If we come across a read request while we are bound to a write server # we need to detach and rebind with a read server from the read pool } elseif {![class match -- $msgtype equals ldap_writes] and $writing == 1} { if {$static::ldap_debug} {log local0. "Rebinding with: ldap_read"} set rebind 1 set writing 0 set replayop $payload TCP::payload replace 0 [TCP::payload length] $binding LB::detach pool $static::readPool } TCP::release TCP::collect } when SERVER_CONNECTED { # A change in the type of request has been detected # requiring a rebind, we've sent the bind now we need to # wait for the response before we send the actual request if { $rebind == 1 } { TCP::collect } } when SERVER_DATA { if { $rebind == 1 } { set rebind 0 # See above for details on this block. Stupid iRules, no proc grrrr set payload [TCP::payload] # Pull the first 2 bytes. binary scan $payload H2c ber_t ber_len set len_bytes 0 if { [expr {[expr {($ber_len + 0x100) % 0x100}]} & 128] > 0 } { set len_bytes [expr {[expr ($ber_len + 0x100) % 0x100]} & 127] } binary scan $payload x[expr {3 + $len_bytes}]c msgid_bytes binary scan $payload x[expr {4 + $len_bytes + $msgid_bytes}]c msgtype set msgtype [expr {$msgtype & 31}] # If the msgtype we have here is for a bind response just discard # it as we don't need to send it to the client if {$msgtype == 1 } { TCP::payload replace 0 [TCP::payload length] "" } # Now send the actual read or write op to the server # It should now have processed the bind TCP::respond $replayop } TCP::release } # v10 CMP compatible version when RULE_INIT { # Read Pool set static::readPool sun_ldap_read # Write Pool set static::writePool sun_ldap_write # Turn on debugging set static::ldap_debug 0 # A lookup table for debugging array set static::msg_types { 0 "bind request" 1 "bind response" 2 "unbind request" 3 "search request" 4 "search response" 6 "modify request" 7 "modify response" 8 "add request" 9 "add response" 10 "delete request" 11 "delete response" 12 "modifydn request" 13 "modifydn response" 14 "compare request" 15 "compare response" 16 "abandon request" 23 "extended request" 24 "extended response" } } when CLIENT_ACCEPTED { set rebind 0 set binding "" set replayop "" set writing 0 TCP::collect } when CLIENT_DATA { # Grab the current payload collected set payload [TCP::payload] # Pull the first 2 bytes. binary scan $payload H2c ber_t ber_len # The first byte is the tag signifying an LDAP message, # Always is hex 30, if that is not so reject if { $ber_t ne "30" } { reject return } # The second byte is one of two values: # a) The length of the packet minus the above # defining byte and the length byte # OR # b) an octet describing how many subsequent bytes # hold the packet length # In either case the message type (what we are after) # follows the message id field which too can be a variable # number of bytes. set len_bytes 0 if { [expr [expr ($ber_len + 0x100) % 0x100] & 128] > 0 } { set len_bytes [expr [expr ($ber_len + 0x100) % 0x100] & 127] } # How many bytes is the message id binary scan $payload x[expr 3 + $len_bytes]c msgid_bytes # The message type is then 4 bytes + number length bytes + number of # message id bytes offset. binary scan $payload x[expr 4 + $len_bytes + $msgid_bytes]c msgtype # msgtype - BER encoded value, bits 1-5 are the actual # type, 6 is the data type, 7-8 are the data class # Here we only care about the lower 5 bits set msgtype [expr $msgtype & 31] if {$static::ldap_debug and [catch { log local0. "message type is: $static::msg_types($msgtype) $msgtype" } ] } { log local0. "Bad message type: $msgtype" reject } # Each connection should start with a bind request # We'll save this packet for later rebinding when we # flip between servers if { $msgtype == 0 } { if {$static::ldap_debug} {log local0. "Bind Request with: ldap_read"} set writing 0 set rebind 0 set binding $payload LB::detach pool $static::readPool # If we come across a write request and are currently not # sending data to the write pool, detach, and set the rebind # flag so we can send the bind packet before we actually send # our write request } elseif {[matchclass $msgtype equals $::ldap_writes] and $writing != 1} { if {$static::ldap_debug} {log local0. "Rebinding with: ldap_write"} set rebind 1 set writing 1 set replayop $payload TCP::payload replace 0 [TCP::payload length] $binding LB::detach pool $static::writePool # If we come across a read request while we are bound to a write server # we need to detach and rebind with a read server from the read pool } elseif {![matchclass $msgtype equals $::ldap_writes] and $writing == 1} { if {$static::ldap_debug} {log local0. "Rebinding with: ldap_read"} set rebind 1 set writing 0 set replayop $payload TCP::payload replace 0 [TCP::payload length] $binding LB::detach pool $static::readPool } TCP::release TCP::collect } when SERVER_CONNECTED { # A change in the type of request has been detected # requiring a rebind, we've sent the bind now we need to # wait for the response before we send the actual request if { $rebind == 1 } { TCP::collect } } when SERVER_DATA { if { $rebind == 1 } { set rebind 0 # See above for details on this block. Stupid iRules, no proc grrrr set payload [TCP::payload] # Pull the first 2 bytes. binary scan $payload H2c ber_t ber_len set len_bytes 0 if { [expr [expr ($ber_len + 0x100) % 0x100] & 128] > 0 } { set len_bytes [expr [expr ($ber_len + 0x100) % 0x100] & 127] } binary scan $payload x[expr 3 + $len_bytes]c msgid_bytes binary scan $payload x[expr 4 + $len_bytes + $msgid_bytes]c msgtype set msgtype [expr $msgtype & 31] # If the msgtype we have here is for a bind response just discard # it as we don't need to send it to the client if {$msgtype == 1 } { TCP::payload replace 0 [TCP::payload length] "" } # Now send the actual read or write op to the server # It should now have processed the bind TCP::respond $replayop } TCP::release } # v9 compatible version when RULE_INIT { # Read Pool set ::readPool sun_ldap_read # Write Pool set ::writePool sun_ldap_write # Turn on debugging set ::debug 0 # A lookup table for debugging array set ::msg_types { 0 "bind request" 1 "bind response" 2 "unbind request" 3 "search request" 4 "search response" 6 "modify request" 7 "modify response" 8 "add request" 9 "add response" 10 "delete request" 11 "delete response" 12 "modifydn request" 13 "modifydn response" 14 "compare request" 15 "compare response" 16 "abandon request" 23 "extended request" 24 "extended response" } } when CLIENT_ACCEPTED { set rebind 0 set binding "" set replayop "" set writing 0 TCP::collect } when CLIENT_DATA { # Grab the current payload collected set payload [TCP::payload] # Pull the first 2 bytes. binary scan $payload H2c ber_t ber_len # The first byte is the tag signifying an LDAP message, # Always is hex 30, if that is not so reject if { $ber_t ne "30" } { reject return } # The second byte is one of two values: # a) The length of the packet minus the above # defining byte and the length byte # OR # b) an octet describing how many subsequent bytes # hold the packet length # In either case the message type (what we are after) # follows the message id field which too can be a variable # number of bytes. set len_bytes 0 if { [expr [expr ($ber_len + 0x100) % 0x100] & 128] > 0 } { set len_bytes [expr [expr ($ber_len + 0x100) % 0x100] & 127] } # How many bytes is the message id binary scan $payload x[expr 3 + $len_bytes]c msgid_bytes # The message type is then 4 bytes + number length bytes + number of # message id bytes offset. binary scan $payload x[expr 4 + $len_bytes + $msgid_bytes]c msgtype # msgtype - BER encoded value, bits 1-5 are the actual # type, 6 is the data type, 7-8 are the data class # Here we only care about the lower 5 bits set msgtype [expr $msgtype & 31] if {$::debug and [catch { log local0. "message type is: $::msg_types($msgtype) $msgtype" } ] } { log local0. "Bad message type: $msgtype" reject } # Each connection should start with a bind request # We'll save this packet for later rebinding when we # flip between servers if { $msgtype == 0 } { if {$::debug} {log local0. "Bind Request with: ldap_read"} set writing 0 set rebind 0 set binding $payload LB::detach pool $::readPool # If we come across a write request and are currently not # sending data to the write pool, detach, and set the rebind # flag so we can send the bind packet before we actually send # our write request } elseif {[matchclass $msgtype equals $::ldap_writes] and $writing != 1} { if {$::debug} {log local0. "Rebinding with: ldap_write"} set rebind 1 set writing 1 set replayop $payload TCP::payload replace 0 [TCP::payload length] $binding LB::detach pool $::writePool # If we come across a read request while we are bound to a write server # we need to detach and rebind with a read server from the read pool } elseif {![matchclass $msgtype equals $::ldap_writes] and $writing == 1} { if {$::debug} {log local0. "Rebinding with: ldap_read"} set rebind 1 set writing 0 set replayop $payload TCP::payload replace 0 [TCP::payload length] $binding LB::detach pool $::readPool } TCP::release TCP::collect } when SERVER_CONNECTED { # A change in the type of request has been detected # requiring a rebind, we've sent the bind now we need to # wait for the response before we send the actual request if { $rebind == 1 } { TCP::collect } } when SERVER_DATA { if { $rebind == 1 } { set rebind 0 # See above for details on this block. Stupid iRules, no proc grrrr set payload [TCP::payload] # Pull the first 2 bytes. binary scan $payload H2c ber_t ber_len set len_bytes 0 if { [expr [expr ($ber_len + 0x100) % 0x100] & 128] > 0 } { set len_bytes [expr [expr ($ber_len + 0x100) % 0x100] & 127] } binary scan $payload x[expr 3 + $len_bytes]c msgid_bytes binary scan $payload x[expr 4 + $len_bytes + $msgid_bytes]c msgtype set msgtype [expr $msgtype & 31] # If the msgtype we have here is for a bind response just discard # it as we don't need to send it to the client if {$msgtype == 1 } { TCP::payload replace 0 [TCP::payload length] "" } # Now send the actual read or write op to the server # It should now have processed the bind TCP::respond $replayop } TCP::release }1.8KViews1like7CommentsProxyPass for use with APM
Problem this snippet solves: This is a specially modified version of the LTM ProxyPass iRule designed to work with a virtual server with an APM access profile applied. Please see the LTM ProxyPass iRule for documentation. Code : # ProxyPass APM iRule, Version 10.9 # Nov 30 2012 # THIS VERSION REQUIRES APM v10 or higher. Use ProxyPass v8.2 for TMOS 9.x. # This version is for APM-enabled virtual servers only! # # APM provides ACCESS_ACL_ALLOWED event for the requests that have passed through access control checks. # This event is semantically equivalent to HTTP_REQUEST event and is triggered for each HTTP request # that has been allowed to go to backend server after session/policy/ACL checks. # All HTTP request processing commands are available in ACCESS_ACL_ALLOWED. (HTTP::header etc.) # We use ACCESS::respond instead of HTTP::redirect/HTTP::respond. # To port the LTM ProxyPass iRule, change HTTP_REQUEST to ACCESS_ACL_ALLOWED and replace HTTP::redirect/HTTP::respond to ACCESS::respond. # # Created by Kirk Bauer # https://devcentral.f5.com/s/wiki/iRules.ProxyPass_for_use_with_APM.ashx # (please see end of iRule for additional credits) # Purpose: # iRule to replace the functionality of Apache Webserver ProxyPass and # ProxyPassReverse functions. It allows you to perform host name and path name # modifications as HTTP traffic passes through the LTM. In other words, you # can have different hostnames and directory names on the client side as you # do on the server side and ProxyPass handles the necessary translations. # NOTE: You should not need to modify this iRule in any way except the settings # in the RULE_INIT event. Just apply the iRule to the virtual server and # define the appropriate Data Group and you are done. If you do make any # changes to this iRule, please send your changes and reasons to me so that # I may understand how ProxyPass is being used and possibly incorporate your # changes into the core release. # Configuration Requirements # 1) The ProxyPass iRule needs to be applied to an HTTP virtual server or # an HTTPS virtual server with a clientssl profile applied to it. # 2) A data group (LTM -> iRules -> Data Groups tab) must be defined with # the name "ProxyPassVIRTUAL" where VIRTUAL is the name of the virtual server # (case-sensitive!). See below for the format of this data group (class). # For 10.0.x, you must use an EXTERNAL data group. # 3) You must define a default pool on the virtual server unless you specify # a pool in every entry in the data group. # 4) If you are using ProxyPass to select alternate pools, you must define # a OneConnect profile in most cases! # 5) ProxyPass does not rewrite links embedded within pages by default, just # headers. If you want to change this, edit the $static::RewriteResponsePayload variable in RULE_INIT # and apply the default stream profile to the virtual server. # Data Group Information # For 10.0.x, you must define an external data group (type=String, read-only) which loads # from a file on your BIG-IP. For 10.1 and higher you can use an internal string data group with name=value pairings. # The format of the file is as follows: # "clientside" := "serverside", # or # "clientside" := "serverside poolname", # The clientside and serverside fields must contain a URI (at least a "/") and # may also contain a hostname. Here are some examples: # "/clientdir" := "/serverdir", # "www.host.com/clientdir" := "internal.company.com/serverdir", # "www.host.com/" := "internal.company.com/serverdir/", # Notes: # 1) You can optionally define a ProxyPassSNATs data group to SNAT based # on the pool selected. # 2) You can optionally define a ProxyPassSSLProfiles data group to select # a serverssl profile based on the pool selected. # 3) You can also use regular expressions which is documented on DevCentral. when RULE_INIT { # Enable to debug ProxyPass translations via log messages in /var/log/ltm # (2 = verbose, 1 = essential, 0 = none) set static::ProxyPassDebug 0 # Enable to rewrite page content (try a setting of 1 first) # (2 = attempt to rewrite host/path and just /path, 1 = attempt to rewrite host/path) set static::RewriteResponsePayload 0 } when CLIENT_ACCEPTED { # Get the default pool name. This is used later to explicitly select # the default pool for requests which don't have a pool specified in # the class. set default_pool [LB::server pool] # The name of the Data Group (aka class) we are going to use. # Parse just the virtual server name by stripping off the folders (if present) set clname "ProxyPass[URI::basename [virtual name]]" if { $static::ProxyPassDebug > 1 } { log local0. "[virtual name]: [IP::client_addr]:[TCP::client_port] -> [IP::local_addr]:[TCP::local_port]" } } when HTTP_REQUEST { # "bypass" tracks whether or not we made any changes inbound so we # can skip changes on the outbound traffic for greater efficiency. set bypass 1 } when ACCESS_ACL_ALLOWED { # Initialize other local variables used in this rule set orig_uri "[HTTP::uri]" set orig_host "[HTTP::host]" set log_prefix "VS=[virtual name], Host=$orig_host, URI=$orig_uri" set clientside "" set serverside "" set newpool "" set ppass "" if {! [class exists $clname]} { log local0. "$log_prefix: Data group $clname not found, exiting." pool $default_pool return } else { set ppass [class match -element "$orig_host$orig_uri" starts_with $clname] if {$ppass eq ""} { # Did not find with hostname, look for just path set ppass [class match -element "$orig_uri" starts_with $clname] } if {$ppass eq ""} { # No entries found if { $static::ProxyPassDebug > 0 } { log local0. "$log_prefix: No rule found, using default pool $default_pool and exiting" } pool $default_pool return } } # Store each entry in the data group line into a local variable set clientside [getfield $ppass " " 1] set serverside [string trimleft [getfield $ppass " " 2 ] "{" ] set newpool [string trimright [getfield $ppass " " 3 ] "}" ] # If serverside is in the form =match=replace=, apply regex if {$serverside starts_with "="} { set regex [getfield $serverside "=" 2] set rewrite [getfield $serverside "=" 3] if {[regexp -nocase $regex "$orig_host$orig_uri" 0 1 2 3 4 5 6 7 8 9]}{ # The clientside becomes the matched string and the serverside the substitution set clientside $0 set serverside [eval set X $rewrite] } else { pool $default_pool return } } if {$clientside starts_with "/"} { # No virtual hostname specified, so use the Host header instead set host_clientside $orig_host set path_clientside $clientside } else { # Virtual host specified in entry, split the host and path set host_clientside [getfield $clientside "/" 1] set path_clientside [substr $clientside [string length $host_clientside]] } # At this point $host_clientside is the client hostname, and $path_clientside # is the client-side path as specified in the data group set host_serverside [getfield $serverside "/" 1] set path_serverside [substr $serverside [string length $host_serverside]] if {$host_serverside eq ""} { set host_serverside $host_clientside } # At this point $host_serverside is the server hostname, and $path_serverside # is the server-side path as specified in the data group # In order for directory redirects to work properly we have to be careful with slashes if {$path_clientside equals "/"} { # Make sure serverside path ends with / if clientside path is "/" if {!($path_serverside ends_with "/")} { append path_serverside "/" } } else { # Otherwise, neither can end in a / (unless serverside path is just "/") if {!($path_serverside equals "/")} { if {$path_serverside ends_with "/"} { set path_serverside [string trimright $path_serverside "/"] } if {$path_clientside ends_with "/"} { set path_clientside [string trimright $path_clientside "/"] } } } if { $static::ProxyPassDebug } { log local0. "$log_prefix: Found Rule, Client Host=$host_clientside, Client Path=$path_clientside, Server Host=$host_serverside, Server Path=$path_serverside" } # If you go to http://www.domain.com/dir, and /dir is a directory, the web # server will redirect you to http://www.domain.com/dir/. The problem is, with ProxyPass, if the client-side # path is http://www.domain.com/dir, but the server-side path is http://www.domain.com/, the server will NOT # redirect the client (it isn't going to redirect you to http://www.domain.com//!). Here is the problem with # that. If there is an image referenced on the page, say logo.jpg, the client doesn't realize /dir is a directory # and as such it will try to load http://www.domain.com/logo.jpg and not http://www.domain.com/dir/logo.jpg. So # ProxyPass has to handle the redirect in this case. This only really matters if the server-side path is "/", # but since we have the code here we might as well offload all of the redirects that we can (that is whenever # the client path is exactly the client path specified in the data group but not "/"). if {$orig_uri eq $path_clientside} { if {([string index $path_clientside end] ne "/") and not ($path_clientside contains ".") } { set is_https 0 if {[PROFILE::exists clientssl] == 1} { set is_https 1 } # Assumption here is that the browser is hitting http://host/path which is a virtual path and we need to do the redirect for them if {$is_https == 1} { ACCESS::respond 302 Location "https://$orig_host$orig_uri/" if { $static::ProxyPassDebug } { log local0. "$log_prefix: Redirecting to https://$orig_host$orig_uri/" } } else { ACCESS::respond 302 Location "http://$orig_host$orig_uri/" if { $static::ProxyPassDebug } { log local0. "$log_prefix: Redirecting to http://$orig_host$orig_uri/" } } return } } if {$host_clientside eq $orig_host} { if {$orig_uri starts_with $path_clientside} { set bypass 0 # Take care of pool selection if {$newpool eq ""} { pool $default_pool if { $static::ProxyPassDebug > 1 } { log local0. "$log_prefix: Using default pool $default_pool" } set newpool $default_pool } else { pool $newpool if { $static::ProxyPassDebug > 0 } { log local0. "$log_prefix: Using parsed pool $newpool (make sure you have OneConnect enabled)" } } } } # If we did not match anything, skip the rest of this event if {$bypass} { return } # The following code will look up SNAT addresses from # the data group "ProxyPassSNATs" and apply them. # # The format of the entries in this list is as follows: # # # # All entries are separated by spaces, and both items # are required. set class_exists_cmd "class exists ProxyPassSNATs" if {! [eval $class_exists_cmd]} { return } set snat [findclass $newpool ProxyPassSNATs " "] if {$snat eq ""} { # No snat found, skip rest of this event return } if { $static::ProxyPassDebug > 0 } { log local0. "$log_prefix: SNAT address $snat assigned for pool $newpool" } snat $snat } when HTTP_REQUEST_SEND { # If we didn't match anything, skip the rest of this event if {$bypass} { return } # The following code does the actual rewrite on its way TO # the backend server. It replaces the URI with the newly # constructed one and masks the "Host" header with the FQDN # the backend pool server wants to see. # # If a new pool or custom SNAT are to be applied, these are # done here as well. If a SNAT is used, an X-Forwarded-For # header is attached to send the original requesting IP # through to the server. if {$host_clientside eq $orig_host} { if {$orig_uri starts_with $path_clientside} { if { $static::ProxyPassDebug > 1 } { log local0. "$log_prefix: New Host=$host_serverside, New Path=$path_serverside[substr $orig_uri [string length $path_clientside]]" } clientside { # Rewrite the URI HTTP::uri $path_serverside[substr $orig_uri [string length $path_clientside]] # Rewrite the Host header HTTP::header replace Host $host_serverside # Now alter the Referer header if necessary if { [HTTP::header exists "Referer"] } { set protocol [URI::protocol [HTTP::header Referer]] if {$protocol ne ""} { set client_path [findstr [HTTP::header "Referer"] $host_clientside [string length $host_clientside]] if {$client_path starts_with $path_clientside} { if { $static::ProxyPassDebug > 1 } { log local0. "$log_prefix: Changing Referer header: [HTTP::header Referer] to $protocol://$host_serverside$path_serverside[substr $client_path [string length $path_clientside]]" } HTTP::header replace "Referer" "$protocol://$host_serverside$path_serverside[substr $client_path [string length $path_clientside]]" } } } } } } # If we're rewriting the response content, prevent the server from using #compression in its response by removing the Accept-Encoding header #from the request. LTM does not decompress response content before #applying the stream profile. This header is only removed if we're #rewriting response content. clientside { if { $static::RewriteResponsePayload } { if { [HTTP::header exists "Accept-Encoding"] } { HTTP::header remove "Accept-Encoding" if { $static::ProxyPassDebug > 1} { log local0. "$log_prefix: Removed Accept-Encoding header" } } } HTTP::header insert "X-Forwarded-For" "[IP::remote_addr]" } } when HTTP_RESPONSE { if { $static::ProxyPassDebug > 1 } { log local0. "$log_prefix: [HTTP::status] response from [LB::server]" } if {$bypass} { # No modification is necessary if we didn't change anything inbound so disable the stream filter if it was enabled # Check if we're rewriting the response if {$static::RewriteResponsePayload} { if { $static::ProxyPassDebug > 1 } { log local0. "$log_prefix: Rewriting response content enabled, but disabled on this response." } # Need to explicity disable the stream filter if it's not needed for this response # Hide the command from the iRule parser so it won't generate a validation error #when not using a stream profile set stream_disable_cmd "STREAM::disable" # Execute the STREAM::disable command. Use catch to handle any errors. Save the result to $result if { [catch {eval $stream_disable_cmd} result] } { # There was an error trying to disable the stream profile. log local0. "$log_prefix: Error disabling stream filter ($result). If you enable static::RewriteResponsePayload, then you should add a stream profile to the VIP. Else, set static::RewriteResponsePayload to 0 in this iRule." } } # Exit from this event. return } # Check if we're rewriting the response if {$static::RewriteResponsePayload} { # Configure and enable the stream filter to rewrite the response payload # Hide the command from the iRule parser so it won't generate a validation error #when not using a stream profile if {$static::RewriteResponsePayload > 1} { set stream_expression_cmd "STREAM::expression \"@$host_serverside$path_serverside@$host_clientside$path_clientside@ @$path_serverside@$path_clientside@\"" } else { set stream_expression_cmd "STREAM::expression \"@$host_serverside$path_serverside@$host_clientside$path_clientside@\"" } set stream_enable_cmd "STREAM::enable" if { $static::ProxyPassDebug > 1 } { log local0. "$log_prefix: \$stream_expression_cmd: $stream_expression_cmd, \$stream_enable_cmd: $stream_enable_cmd" } # Execute the STREAM::expression command. Use catch to handle any errors. Save the result to $result if { [catch {eval $stream_expression_cmd} result] } { # There was an error trying to set the stream expression. log local0. "$log_prefix: Error setting stream expression ($result). If you enable static::RewriteResponsePayload, then you should add a stream profile to the VIP. Else, set static::RewriteResponsePayload to 0 in this iRule." } else { # No error setting the stream expression, so try to enable the stream filter # Execute the STREAM::enable command. Use catch to handle any errors. Save the result to $result if { [catch {eval $stream_enable_cmd} result] } { # There was an error trying to enable the stream filter. log local0. "$log_prefix: error enabling stream filter ($result)" } else { if { $static::ProxyPassDebug > 1 } { log local0. "$log_prefix: Successfully configured and enabled stream filter" } } } } # Fix Location, Content-Location, and URI headers foreach header {"Location" "Content-Location" "URI"} { set protocol [URI::protocol [HTTP::header $header]] if { $static::ProxyPassDebug > 1 } { log local0. "$log_prefix: Checking $header=[HTTP::header $header], \$protocol=$protocol" } if {$protocol ne ""} { set server_path [findstr [HTTP::header $header] $host_serverside [string length $host_serverside]] if {$server_path starts_with $path_serverside} { if { $static::ProxyPassDebug } { log local0. "$log_prefix: Changing response header $header: [HTTP::header $header] with $protocol://$host_clientside$path_clientside[substr $server_path [string length $path_serverside]]" } HTTP::header replace $header $protocol://$host_clientside$path_clientside[substr $server_path [string length $path_serverside]] } } } # Rewrite any domains/paths in Set-Cookie headers if {[HTTP::header exists "Set-Cookie"]}{ array unset cookielist foreach cookievalue [HTTP::header values "Set-Cookie"] { set cookiename [getfield $cookievalue "=" 1] set namevalue "" set newcookievalue "" foreach element [split $cookievalue ";"] { set element [string trim $element] if {$namevalue equals ""} { set namevalue $element } else { if {$element contains "="} { set elementname [getfield $element "=" 1] set elementvalue [getfield $element "=" 2] if {[string tolower $elementname] eq "domain"} { set elementvalue [string trimright $elementvalue "."] if {$host_serverside ends_with $elementvalue} { if {$static::ProxyPassDebug > 1} { log local0. "$log_prefix: Modifying cookie $cookiename domain from $elementvalue to $host_clientside" } set elementvalue $host_clientside } append elementvalue "." } if {[string tolower $elementname] eq "path"} { if {$elementvalue starts_with $path_serverside} { if {$static::ProxyPassDebug > 1} { log local0. "$log_prefix: Modifying cookie $cookiename path from $elementvalue to $path_clientside[substr $elementvalue [string length $path_serverside]]" } set elementvalue $path_clientside[substr $elementvalue [string length $path_serverside]] } } append newcookievalue "; $elementname=$elementvalue" } else { append newcookievalue "; $element" } } } set cookielist($cookiename) "$namevalue$newcookievalue" } HTTP::header remove "Set-Cookie" foreach cookiename [array names cookielist] { HTTP::header insert "Set-Cookie" $cookielist($cookiename) if {$static::ProxyPassDebug > 1} { log local0. "$log_prefix: Inserting cookie: $cookielist($cookiename)" } } } } # Only uncomment this event if you need extra debugging for content rewriting. # This event can only be uncommented if the iRule is used with a stream profile. #when STREAM_MATCHED { #if { $static::ProxyPassDebug } { #log local0. "$log_prefix: Rewriting match: [STREAM::match]" #} #} # The following code will look up SSL profile rules from # the Data Group ProxyPassSSLProfiles" and apply # them. # # The format of the entries in this list is as follows: # # # # All entries are separated by spaces, and both items # are required. The virtual server also will need to # have any serverssl profile applied to it for this to work. when SERVER_CONNECTED { if {$bypass} { return } set class_exists_cmd "class exists ProxyPassSSLProfiles" if {! [eval $class_exists_cmd]} { return } set pool [LB::server pool] set profilename [findclass $pool ProxyPassSSLProfiles " "] if {$profilename eq ""} { if { [PROFILE::exists serverssl] == 1} { # Hide this command from the iRule parser (in case no serverssl profile is applied) set disable "SSL::disable serverside" catch {eval $disable} } return } if { $static::ProxyPassDebug > 0 } { log local0. "$log_prefix: ServerSSL profile $profilename assigned for pool $pool" } if { [PROFILE::exists serverssl] == 1} { # Hide these commands from the iRule parser (in case no serverssl profile is applied) set profile "SSL::profile $profilename" catch {eval $profile} set enable "SSL::enable serverside" catch {eval $enable} } else { log local0. "$log_prefix: ServerSSL profile must be defined on virtual server to enable server-side encryption!" } } # ProxyPass Release History #v10.9: Nov 26, 2012: Used URI::basename to get the virtual server name. Thanks to Opher Shachar for the suggestion. #Replaced indentations with tabs intead of spaces to save on characters #v10.8: Oct 25, 2012: Updated the class name to remove the folder(s) (if present) from the virtual server name. # This assumes the ProxyPass data group is in the same partition as the iRule. #v10.7: Oct 24, 2012: Changed array set cookielist {} to array unset cookielist as the former does not clear the array. # Thanks to rhuyerman@schubergphilis.com and Simon Kowallik for pointing out the issue and this wiki page with details: http://wiki.tcl.tk/724 #v10.6: Oct 14, 2012: Updated how the protocol is parsed from URLs in request and response headers to fix errant matches #v10.5: Feb 2, 2012: Removed extra stream profile $result reference for debug logging. #v10.4: Nov 23, 2011: Removed an extra colon in sever HTTP::header replace commands to prevent duplicate headers from being inserted #v10.3: Sep 27, 2010: Moved rewrite code to HTTP_REQUEST_SEND to work with WebAccelerator # Fixed bug with cookie rewrites when cookie value contained an "=" #v10.2: Jun 04, 2010: Can handle individual file mappings thanks to Michael Holmes from AZDOE # Also fixed bug with directory slash logic #v10.1: Oct 24, 2009: Now CMP-friendly! (NOTE: use ProxyPass v8.2 for TMOS v9.x) #v10.0: May 15, 2009: Optimized for external classes in v10 only (use v8.2 for TMOS v9.x) # Added support for regular expressions and backreferences for the translations. # v8.2: Jun 04, 2010: Fixed bug with directory slash logic # v8.1: May 15, 2009: Added internal redirects back in (removing them was a mistake) # v8.0: May 13, 2009: pulled in changes submitted by Aaron Hooley (hooleylists gmail com) # TMOS v10 support added. Cookie domain/path rewriting added. # v7.0: May 6, 2008: added optional serverssl contributed by Joel Moses # v6.0: Jan 15, 2008: Small efficiency change # v5.0: Jul 27, 2007: Added Referer header conversions # v4.0: Jul 27, 2007: Added optional debugging flag # v3.0: Jul 20, 2007: Added SNAT support contributed by Adam Auerbach # v2.0: May 28, 2007: Added internal directory redirects and optional stream profile # v1.0: Feb 20, 2007: Initial Release515Views0likes1CommentNTLM Authenticated Proxy External Monitor
Problem this snippet solves: NTLM Authenticated Proxy External Monitor How to use this snippet: This monitor is used to monitor the availability of a web page through a NTLM authenticated proxy. The default HTTP monitor relies on receiving a 401 Authenticate message to trigger the NTLM handshake, proxies respond with a 407 Proxy Authenticate message instead, which causes the monitor to fail. Set the following variable: URI-The requested host/page to send the request to. (e.g. www.host.com/page1 or https://www.host.com/page.html) USER-Proxy Username PASS-Proxy Password RECV-Receive String to look for Code : #!/bin/sh # #Name:external_monitor_NTLM_Proxyauth #Author:Matt Elkington #Contact:melkington@integrity360.com #Date:23/01/2017 #Description:An external monitor to allow monitoring of a host through a NTLM Authenticated proxy #This is to work around the fact that the standard http monitor will only use NTLM if #it receives a 401 Authenticate message and ignores a 407 Proxy Authenticate message # #Change Log #VersionChangeDate #1.0Initial Monitor23/01/2017 # # #Port and IP address are supplied automatically a variables $1 and $2 byt the LTM: #$1 = IP (nnn.nnn.nnn.nnn notation) #$2 = port (decimal, host byte order) # #The following variables must be set in the monitor definitation: # #URI-The requested host/page to send the request to. (e.g. www.host.com/page1 or https://www.host.com/page.html) #USER-Proxy Username #PASS-Proxy Password #RECV-Receive String to look for # # remove IPv6/IPv4 compatibility prefix (LTM passes addresses in IPv6 format) NODE=`echo ${1} | sed 's/::ffff://'` PORT=${2} PIDFILE="/var/run/`basename ${0}`.${NODE}_${PORT}.pid" # kill of the last instance of this monitor if hung and log current pid if [ -f $PIDFILE ] then echo "EAV exceeded runtime needed to kill ${IP}:${PORT}" | logger -p local0.error kill -9 `cat $PIDFILE` > /dev/null 2>&1 fi echo "$$" > $PIDFILE # send request & check for expected response curl ${URI} --proxy ${NODE}:${PORT} -U ${USER}:${PASS} --proxy-ntlm -k | grep -i "${RECV}" 2>&1 > /dev/null # mark node UP if expected response was received if [ $? -eq 0 ] then # Remove the PID file rm -f $PIDFILE echo "UP" else # Remove the PID file rm -f $PIDFILE fi exit Tested this on version: 11.6672Views0likes0CommentsSMTP Proxy - Send to specific pool based on sender domain
Problem this snippet solves: The following iRule is based on the SMTPProxy iRule found in the CodeShare, and will route mail to a specific pool based on the domain found in the FROM header. This rule supports RSET only PRIOR to the first FROM header being sent by the client. The LTM hands off the SMTP connection to the pool member after the FROM header is sent. Subsequent messages through the same connection (using RSET) will be handled by the same pool member. Code : class MailAddrList { { "f5.com" { "SMTP_POOL3" } "cisco.com" { "SMTP_POOL1" } "jonny.com" { "SMTP_POOL2" } } } rule SMTPProxy_BalanceOnFromAddr { # # Based on iRule from devcentral.f5.com (http://devcentral.f5.com/s/wiki/default.aspx/iRules/SMTPProxy.html) # Edited by Terje Gravvold for Trygdeetaten/NAV 2006 # Edited by James Denton for Rackspace/2011 # # Version 0.3.20111101 (Not production stable, only for testing) # # To-do: # * Write more effective regexps, reduce amount of regsub and regexp calls. # * Implement better and more unified logging (More log levels?) # * Implement proper SMTP RSET handling. # * Implement proper SMTP NOOP handling (if it we should support it). # * General code optimalization. # * SMTP address syntax checking? regexps form http://www.regular-expressions.info/email.html # # Whats new: # * Regexps related to SMTP command checking is substituted with string commands. Much better performance. # * Fixed some minor errors in logging. # * Some code optimalisation. # * (JD) Replaced matchclass commands with class commands for v10+ optimization # * (JD) Only evaluate MAIL FROM to make a LB decision # # What's been removed: # * RblListIP # * BlockFromUser # # Remember to define these iRule Data Group Lists: # * (JD) MailAddrList - List of mail rcpt addresses to loadbalance to a special pool (type=string) # # When the client is accepted by the system: # - Initiate variables for later use. # - Respond to to the client with a SMTP greeting. # - Start collecting TCP data. # when CLIENT_ACCEPTED { set chelo "" set cfrom "" set cdata "" # Set log level 0=none, 1=log rejects, 2=debug set debug "2" set myorg "AppRiver" set mymailhost "mail.appriver.com" set client_quit 0 set ehlo 0 TCP::respond "220 F5 mail proxy for $myorg. Please report issues to $myorg technical support.\r\n" if { $debug >= 2 } { log local0. "client [IP::client_addr] accepted" } TCP::collect } # # This section handles the clientside connection, that is TCP data between client and BigIP. # when CLIENT_DATA { set cdata [TCP::payload] # # Return on empty payload. # if { [ string length [TCP::payload] ] <= 0 } { return } # # If payload doesn't contain carriage return we have to collect more data, return. # if { not ( [TCP::payload] contains "\r\n" ) } { return } # # HELO - Catch SMTP HELO/EHLO commands # if { [string match -nocase "HELO*" [TCP::payload]] } { set chelo [TCP::payload] if { $debug >= 2 } { log local0. "get helo <$cdata>" } TCP::respond "250 $mymailhost. Hello!\r\n" TCP::payload replace 0 [string length [TCP::payload]] "" set ehlo 0 return } if { [string match -nocase "EHLO*" [TCP::payload]] } { set chelo [TCP::payload] if { $debug >= 2 } { log local0. "get helo <$cdata>" } TCP::respond "250-$mymailhost\r\n" TCP::payload replace 0 [string length [TCP::payload]] "" set ehlo 1 return } # # NOOP - Do nothing? great! # if { [string match -nocase "NOOP*" $cdata] } { if { $debug >= 2 } { log local0. "NOOP - Doing nothing, tralala..." } TCP::respond "250 Ok\r\n" TCP::payload replace 0 [string length [TCP::payload]] "" return } # # RSET - Clear prior data # if { [string match -nocase "RSET*" $cdata] } { if { $debug >= 2 } { log local0. "RSET - Clear variables..." } set cfrom "" set cdata "" TCP::respond "250 OK\r\n" TCP::payload replace 0 [string length [TCP::payload]] "" return } # # QUIT - See you later... # if { [string match -nocase "QUIT*" $cdata] } { if { $debug >= 2 } { log local0. "QUIT recived from client, closing connection to [IP::client_addr]." } TCP::respond "221 Bye\r\n" TCP::payload replace 0 [string length [TCP::payload]] "" set client_quit 1 TCP::close return } # # MAIL FROM - Who's calling? # if { [string match -nocase "MAIL FROM:*" $cdata] } { set cfrom [TCP::payload] set fromaddr [regsub -all \[\\r\\n\\s\] $cfrom ""] set fromaddr [findstr $fromaddr ":" 1] set fromdomain [findstr $fromaddr "@" 1] if { $fromaddr equals "" } { if { $debug >= 2 } { log local0. "Empty from address not allowed." } TCP::respond "501 Syntax: MAIL FROM: \r\n" TCP::payload replace 0 [string length $cfrom] "" set cfrom "" return } if { $debug >= 2 } { log local0. "get from <$cfrom>" } if { $debug >= 2 } { log local0. "From domain: <$fromdomain>" } TCP::respond "250 OK\r\n" TCP::payload replace 0 [string length $cfrom] "" # If the MAIL FROM address equals a string from the MailAddrList string class, # then load balance the connection to the specified pool in the class for further processing. if { [ class match $fromdomain equals "MailAddrList" ] } { set smtp_pool [ class match -value -- $fromdomain equals "MailAddrList" ] pool $smtp_pool set server_ip [LB::server addr] if { $debug >= 2 } { log local0. "Pool [LB::server pool] selected..." } } else { if { $debug >= 2 } { log local0. "Default pool [LB::server pool] selected..." } } TCP::payload replace 0 0 $chelo$cfrom if { $debug >= 2 } { log local0. "Client = [IP::client_addr], Payload = <[TCP::payload]>" } TCP::release if { $debug >= 2 } { log local0. "Releasing data from client ([IP::client_addr]) to server ([IP::server_addr])." } #TCP::collect } else { if { $debug >= 2 } { log local0. "Syntax error - Invalid SMTP command [TCP::payload]." } TCP::respond "502 Error: command not implemented\r\n" TCP::payload replace 0 [string length [TCP::payload]] "" return } } # # Serverside connection handling # when SERVER_CONNECTED { if { $debug >= 2 } { log "Server [IP::server_addr] connected" } TCP::collect } when SERVER_DATA { set sdata [TCP::payload] # Filter SMTP 220 status messages from server to client. We have already sent HELO/EHLO reply. if { $sdata starts_with "220" } { log local0. "get data <$sdata>" TCP::payload replace 0 [string length $sdata] "" return } # Filter all 250 status messages from server to client. We've sent them before. Keep everything else. if { $sdata starts_with "250-" or "250 " } { if { $debug >= 2 } { log local0. "sdata before filter <$sdata>" } set reg1 "\[\\r\\n\]" set reg2 "\[\{\]" set reg3 "\[\}\\s\]" set reg4 "\[\}\]" set fltsdata "" set fltsdata $fltsdata[regexp -all -line -inline (?!^250.*)^.* $sdata] set fltsdata [regsub -all $reg1 $fltsdata ""] set fltsdata [regsub -all $reg2 $fltsdata ""] set fltsdata [regsub -all $reg3 $fltsdata "\r\n"] set fltsdata [regsub -all $reg4 $fltsdata ""] if { $debug >= 2 } { log local0. "sdata after filter <$fltsdata>" } TCP::payload replace 0 [string length $sdata] $fltsdata if { $debug >= 2 } { log local0. "TCP payload = [TCP::payload]" } TCP::release return } if { [ string length $sdata ] <= 0 } { return } if { $debug >= 2 } { log local0. "payload from server to client <[TCP::payload]>" } TCP::release TCP::collect } when CLIENT_CLOSED { if { $client_quit } { if { $debug >= 2 } { log local0. "client [IP::client_addr] closed connection before server connected." } } else { if { $debug >= 2 } { log local0. "client [IP::client_addr] closed connection to server." } } } }1.5KViews0likes1CommentReverse Proxy With Basic SSO
Problem this snippet solves: The iRule implements a authenticated HTTPS reverse proxy. This iRule respond to a possible use of BigIP as an authenticated HTTPS reverse proxy. At this point, the iRule rewrite Host and Location in HTTP::header, support virtual multihosting and basic single sign-on. First, declare two classes for rewrite HTTP::header Host and HTTP::header Location How to use this snippet: Supporting Classes class tab_hostrewrite extern { type string filename "tab_hostrewrite.txt" } class tab_locationrewrite extern { type string filename "tab_locationrewrite.txt" } The 'extern' keyword is not required in 9.4.x versions when creating the class from the CLI. For "Host" rewriting, the file format is specific to our use (no DNS use), example: "host1.mydomain.com ws1.inet.mydomain.com 192.168.1.14 80", "host2.mydomain.com ws2.inet.mydomain.com 192.168.1.11 80", For "Location" rewriting, an example is: "ws2.inet.mydomain.com https://host2.mydomain.com", Code : # rule ReverseProxy ########################################################################### ## IRule Reverse Proxy (c)05 F.NOEL - No warranty, feel free to use ## v0.01: F.NOEL - create irules with basic Host and Location rewrite ## 0.02: F.NOEL - add Single Sign ON (need to set :SSO to 1 in RULE_INIT) ## 0.03: F.NOEL - build cookie domain based on HTTP Header "Host" ## - if "Host" not FQDN, cookie's domain set to ::COOKIE_DEFAULT_DOMAIN ## 0.04: F.NOEL - add SSO cookie encryption (AES) ## ########################################################################### when RULE_INIT { set ::DEBUG 0 set ::RP_PRIVIP "192.168.1.254" set ::SSO 1 set ::COOKIE_DEFAULT_DOMAIN ".mydomain.com" set ::COOKIE_NAME "WSSOMYDOMAIN" set ::COOKIE_ENCRYPT 1 set ::AES_KEY [AES::key 256] if { $::DEBUG } { log local0.debug "Initialyze random AES_KEY='$::AES_KEY' " } } when HTTP_REQUEST { set header_auth "" set header_host [HTTP::host] set hostrewrite [findclass $header_host $::tab_hostrewrite " "] if { $hostrewrite ne "" } { set destnodeaddr [getfield $hostrewrite " " 2] set destnodeport [getfield $hostrewrite " " 3] set hostrewrite [getfield $hostrewrite " " 1] HTTP::header replace "Host" $hostrewrite if { $::DEBUG } { log local0.debug "Header Host '$header_host' found -> rewrite with '$hostrewrite'" } snat $::RP_PRIVIP node $destnodeaddr $destnodeport } else { if { $::DEBUG } { log local0.debug "$header_host not found -> respond with 403..." } HTTP::respond 403 content "HTTP Error 403 - Forbidden" } if { $::SSO } { set header_auth [HTTP::header "Authorization"] if { $::DEBUG } { log local0.debug "REQ header_auth -> '$header_auth'" } if { [HTTP::cookie exists $::COOKIE_NAME] } { set SSO_DO_SET_COOKIE 0 HTTP::cookie remove $::COOKIE_NAME if { $::DEBUG } { log local0.debug "REQ cookie_sso exist -> set SSO_DO_SET_COOKIE=0 and remove cookie" } } else { if { $header_auth ne "" } { set SSO_DO_SET_COOKIE 1 if { $::DEBUG } { log local0.debug "REQ cookie_sso not exist -> set SSO_DO_SET_COOKIE=1" } } } } } when HTTP_RESPONSE { ### SSO_DO_SET_COOKIE flag on, set a cookie for support Single Sign ON if { $::SSO and $SSO_DO_SET_COOKIE } { ## extract domain name from host to set cookie domain set cookiedomain $::COOKIE_DEFAULT_DOMAIN for {set i 6} {$i > 1} {incr i -1} { set tmp [getfield $header_host "." $i] ## if Host is FQDN if { $tmp ne "" and $i > 2 } { set cookiedomain $tmp incr i -1 set cookiedomain ".[getfield $header_host "." $i].$cookiedomain" break; } } if { $::DEBUG } { log local0.debug "cookiedomain= '$cookiedomain' " } if { $::COOKIE_ENCRYPT } { set cookie_payload [b64encode [AES::encrypt $::AES_KEY $header_auth]] } else { set cookie_payload $header_auth } if { $::DEBUG } { log local0.debug "cookie_payload= '$cookie_payload' " } HTTP::cookie insert name $::COOKIE_NAME value $cookie_payload HTTP::cookie domain $::COOKIE_NAME $cookiedomain HTTP::cookie path $::COOKIE_NAME "/" set SSO_DO_SET_COOKIE 0 if { $::DEBUG } { log local0.debug "SSO_DO_SET_COOKIE=1 -> insert cookie $::COOKIE_NAME='$cookie_payload' in response..." } } if { [HTTP::status] starts_with "3" } { set location [HTTP::header "Location"] if { $location ne "" } { if { $::DEBUG } { log local0.debug "Header Location '$location' not null -> checking..." } set loc_start "" if { $location starts_with "http://" } { set loc_start "http://" } elseif { $location starts_with "https://" } { set loc_start "https://" } set loc_start_len [string length $loc_start] if { $loc_start_len eq 0 } { if { $::DEBUG } { log local0.debug "No absolute redirection! return... " } return } set loc_end [substr $location $loc_start_len] set loc_to_search [getfield $loc_end "/" 1] set locationrewrite [findclass $loc_to_search $::tab_locationrewrite " "] if { $locationrewrite ne "" } { set loc_to_search_len [string length $loc_to_search] set loc_end [substr $loc_end $loc_to_search_len] set new_loc "$locationrewrite$loc_end" HTTP::header replace "Location" $new_loc if { $::DEBUG } { log local0.debug "Rewrite Location -> $new_loc" } } else { if { $::DEBUG } { log local0.debug "Location not found in tab_locationrewrite -> return..." } } return } } else { return } } # Finally, if you want activate the support for basic single sign-on with a ldap authentication, add rule SSO_Auth_Ldap on your authentication profile # rule SSO_Auth_Ldap ########################################################################### ## IRule Reverse Proxy - AuthLdap (c)05 F.NOEL - No warranty, feel free to use ## v0.01: create irule for support Single Sign ON with LDAP authentication ## ########################################################################### when CLIENT_ACCEPTED { set tmm_auth_ldap_sid [AUTH::start pam default_ldap] } when HTTP_REQUEST { if { [HTTP::cookie exists $::COOKIE_NAME] } { set cookie_payload [HTTP::cookie value $::COOKIE_NAME] if { $::COOKIE_ENCRYPT } { set cookie_payload [AES::decrypt $::AES_KEY [b64decode $cookie_payload]] } if { $::DEBUG } { log local0.debug "cookie $::COOKIE_NAME exist -> set Authorization credential" } HTTP::header replace "Authorization" $cookie_payload } else { if { $::DEBUG } { log local0.debug "cookie $::COOKIE_NAME doesn't exist -> authenticate user" } AUTH::username_credential $tmm_auth_ldap_sid [HTTP::username] AUTH::password_credential $tmm_auth_ldap_sid [HTTP::password] AUTH::authenticate $tmm_auth_ldap_sid HTTP::collect } } when AUTH_SUCCESS { if {$tmm_auth_ldap_sid eq [AUTH::last_event_session_id]} { HTTP::release } } when AUTH_FAILURE { if {$tmm_auth_ldap_sid eq [AUTH::last_event_session_id]} { HTTP::respond 401 } } when AUTH_WANTCREDENTIAL { if {$tmm_auth_ldap_sid eq [AUTH::last_event_session_id]} { HTTP::respond 401 } } when AUTH_ERROR { if {$tmm_auth_ldap_sid eq [AUTH::last_event_session_id]} { HTTP::respond 401 } }988Views0likes0CommentsProxyPass (for LTM v9 only)
Problem this snippet solves: iRule to replace the functionality of Apache Webserver ProxyPass and ProxyPassReverse functions. Allows you to do hostname and pathname modifications as HTTP traffic passes through the LTM. (Full documentation follows the iRule.) For use with TMOS v10 and v11, see ProxyPass v10.9 Introduction Sometimes it is desirable to have a different look and feel to your website on the outside than you have in the inside. You may want www.company.com/usa/ to internally go to the server usa.company.com. You may want support.company.com to go internally to abc123.company.com/web/support. This can create a few issues – sometimes the web server expects to see a certain hostname (i.e. for name-based virtual hosting) or will use the internal hostname and/or path when sending a redirect to the clients. These problems can be overcome with the Apache webserver using the ProxyPass command which can translate the URL on the way into the server, and the ProxyPassReverse command which can un-translate header fields such as Location in the case of a redirect. ProxyPass now handles the domain and path in any cookies set by the server. Now you can accomplish this with an iRule. The ProxyPass iRule will translate incoming requests in a flexible manner and untranslate the Location, Content-Location, and/or URI headers in the response back to the client. Page Content Modification In addition, this rule will perform basic page modification as needed (this feature is disabled by default but can be enabled in the RULE_INIT event). Using the example from the introduction, if the page content contains a link to http://abc123.company.com/web/support/viewticket.html, the iRule will modify that to be http://support.company.com/viewticket.html. It will NOT modify absolute path references that are not full URLs. Here are some examples: < a href=http://www.domain.com/path/file.html> will be modified assuming the incoming request was matched by the ProxyPass iRule and the inside hostname was www.domain.com and the inside path was /path. < a href=”page2.html”> will not need to be modified as this is a URL already relative to the path. Even relative URLs such as < a href=”../page2.html”> will work as long as it does not try to go above the top-level directory defined by the ProxyPass rules. < a href=”/page2.html”> will not be modified and will probably cause the website to break if the user follows this link. In this case you need to modify the website and/or consider a different architecture. You must have a stream profile defined on any virtual servers the rule is applied to in order to enable the page modification feature. Virtual Server The first step to using the ProxyPass iRule is to define the rule on your BIG-IP and associate it with one or more Virtual Servers. Note that each virtual server MUST have an HTTP profile defined (doesn’t matter which one). I also highly recommend applying a OneConnect profile, especially if you will be choosing pools with ProxyPass. It also must have a stream profile associated with it if you want to uncomment the page modification code. The rule will work on HTTP sites as well as HTTPS sites where the SSL is terminated on the BIG-IP (i.e. a client-side SSL profile is defined). Data Groups You can apply the ProxyPass rule to any virtual server that you want to do translations on. But just applying the rule will have no effect unless you define the translations you want done. This is done by defining specific Data Groups. The ProxyPass iRule uses Data Groups which are created and managed by going to Local Traffic / Virtual Servers / iRules on the left menu bar in the BIG-IP GUI. Then choose the "Data Group List" tab at the top of the screen. Here you can create the data groups used by this rule. Note that it uses data groups of type "string" in all cases. In order to use this rule on a virtual server you must apply the rule to the virtual server and create a data group named ProxyPassXYZ where “XYZ” needs to be the name of the virtual server. If both of these conditions are not met then the rule will not work for that virtual server. ProxyPassXYZ Data Groups If your virtual server is named XYZ and has the ProxyPass iRule associated with it, it will look for a data group named ProxyPassXYZ. Assuming that class is found, for each new HTTP request, the rule will find the one row that matches the hostname/path used in the request. For example, the data group may contain 4 entries (each line below is one string in the data group): www.usa.company.com/support support.company-internal.com:8080/usa www.usa.company.com/ www.company-internal.com:8080/usa www.japan.company.com/ www.company-internal.com:8080/japan / www.company-internal.com:8080/others A request need not match any entries – if no entries match then the iRule will have no effect. But each request will only match at most one entry and that will be the entry with the most specific left-hand-side. Entries with hostnames specified on the left-hand-side will be matched before entries without hostnames. If multiple entries match then the entry with the longest path name on the left-hand-side will be used. The example above lists entries from most-specific to least-specific, just as the rule will process them, but in your actual data group the order of the entries does not matter. In the example above, requests to http://www.usa.company.com/support will match the first entry and have the host header changed to “support.company-internal.com:8080” and the URI will be rewritten so that the string /support at the beginning of the URI will be changed to /usa. Furthermore, requests to http://www.usa.company.com/ will match the second entry as long as the URI does not begin with “/support” in which case it would match the first entry. In that case the Host header will be changed to “www.company-internal.com:8080” and whatever URI the client sends in will be prepended with “/usa”. Likewise all requests to http://www.japan.company.com/ will match the third entry and have the Host header changed to “www.company-internal.com:8080” and the URIs would be prepended with “/japan”. Finally, all other requests that hit this example virtual server would match the least-specific rule which is simply “/” – all URIs begin with “/” and thus all requests will match the fourth entry if they did not match any others. Remember that a catch-all entry is not required, but in this example we want to prepend the URI of all other requests with “/others”. Note that the ProxyPass iRule does not actually alter the destination of the requests by default. In the examples above all of the requests would go to the default pool regardless of the entries they match. The hostnames and ports specified in the right-hand entry is only used to modify the Host header. To alter the destination pool see the next section. Dynamic Pool Selection You may also specify an alternate pool as the third item in the entry. This is optional – any items in the list without a pool name will just use the default pool associated with the virtual server. For example: /support support.company.com/ SupportPool /downloads downloads.company.com/ DownloadPool If the pool name is not valid the user will get an error and you should see an error message in /var/log/ltm. Dynamic SNAT There is an optional 4th item for an entry to enable dynamic SNAT. If you specify a SNAT address as the 4th item for an entry then the default SNAT settings of the virtual server will be overridden such that the request will be SNATed to the specified IP address. In addition, an X-Forwarded-For header automatically inserted. For example, the entries: /support support.company.com/ SupportPool 10.10.10.11 /downloads downloads.company.com/ DownloadPool 10.10.10.12 Will cause the requests to be SNATed to 10.10.10.11 or 10.10.10.12 depending on which URI was requested. Dynamic ServerSSL Profiles You can optionally define a ProxyPassSSLProfiles data group and apply a generic serverssl profile to the virtual server. This will allow you to use different serverssl profiles based on which pool you send traffic to. The ProxyPassSSLProfiles data group is shared by all virtual servers but will only have an effect if the selected pool is listed in the data group and a generic serverssl is applied to the virtual server. The format of this data group is: Pool1 ServerSSLProfile1 Pool2 ServerSSLProfile2 Debugging You can debug your ProxyPass rules by setting the ::ProxyPassDebug variable at the top of the rule to 1 (or 2 for more verbose debugging). Once you do this you can SSH in to the BIG-IP and run the command “tail –f /var/log/ltm” to see what ProxyPass is doing to your requests. Code : # ProxyPass iRule, Version 8.2 # June 4, 2010 # Created and Maintained by Kirk Bauer # https://devcentral.f5.com/s/wiki/default.aspx/iRules/ProxyPass.html # (please see end of iRule for additional credits) # Purpose: # iRule to replace the functionality of Apache Webserver ProxyPass and # ProxyPassReverse functions. It allows you to perform host name and path name # modifications as HTTP traffic passes through the LTM. In other words, you # can have different hostnames and directory names on the client side as you # do on the server side and ProxyPass handles the necessary translations. # NOTE: You should not need to modify this iRule in any way unless you # are doing debugging. Just apply the iRule to the virtual server and # define the appropriate Data Group and you are done. If you make any # changes to the iRule, please send them back to me so I can understand # what you changed and why and possibly update the core release. # Configuration Requirements # 1) The ProxyPass iRule needs to be applied to an HTTP virtual server or # an HTTPS virtual server with a clientssl profile applied to it. # 2) A data group (LTM -> iRules -> Data Groups tab) must be defined with # the name "ProxyPassVIRTUAL" where VIRTUAL is the name of the virtual server # (case-sensitive!). See below for the format of this data group (class). # 3) You must define a default pool on the virtual server unless you specify # a pool in every entry in the data group. # 4) If you are using ProxyPass to select alternate pools, you must define # a OneConnect profile in most cases! # 5) ProxyPass does not rewrite links embedded within pages by default, just # redirects. If you want to change this, edit the proper variable in RULE_INIT # and apply the generic "stream" profile to the virtual server. # Data Group Format (must be string-type entries) # clientside serverside [pool] [SNAT IP] # Only the first two fields are required. They always contain a path and # may also contain a hostname. Here are some examples: # /clientdir /serverdir # www.host.com/clientdir internal.company.com/serverdir # www.host.com/ internal.company.com/serverdir/ # Note that the clientside entry only ends in a / if there is no directory. # The server entry only ends in a slash if the client entry does. # Notes: # 1) If you are using TMOS v10.0.0 or later, you must make two changes # below (search for TMOSv10). In addition, I highly recommend upgrading # to ProxyPass v10 if you are running TMOSv10. # 2) This iRule is *not* Cluster Multi-processing (CMP) compatible because # of the global $::ProxyPassDebug setting. In TMOS v10, you can make the # specified change in RULE_INIT and then replace all occurrences of # $::ProxyPassDebug with $static::ProxyPassDebug. In TMOS v9, you can # remove the entire RULE_INIT event and all references to $::ProxyPassDebug # and you will just lose the ability to turn on debugging. You could always # switch back to the original iRule to turn debugging back on. # 3) You can optionally define a ProxyPassSSLProfiles data group to select # a serverssl profile based on the pool selected. when RULE_INIT { # Enable to debug ProxyPass translations via log messages in /var/log/ltm # (2 = verbose, 1 = essential, 0 = none) # TMOSv10: You can optionally change this global variable to a static # to make this iRule CMP-friendly (change references within iRule too). # set static::ProxyPassDebug 0 set ::ProxyPassDebug 0 # Enable to rewrite page content (try a setting of 1 first) # (2 = attempt to rewrite host/path and just /path, 1 = attempt to rewrite host/path) # TMOSv10: You can optionally change this global variable to a static # to make this iRule CMP-friendly (change references within iRule too). # set static::RewriteResponsePayload 0 set ::RewriteResponsePayload 0 } when CLIENT_ACCEPTED { # Get the default pool name. This is used later to explicitly select # the default pool for requests which don't have a pool specified in # the class. set default_pool [LB::server pool] if { $::ProxyPassDebug > 1 } { log local0. "[virtual name]: [IP::client_addr]:[TCP::client_port] -> [IP::local_addr]:[TCP::local_port]" } } when HTTP_REQUEST { # "bypass" tracks whether or not we made any changes inbound so we # can skip changes on the outbound traffic for greater efficiency. set bypass 1 # The name of the Data Group (aka class) we are going to use # TMOSv10: use this line for TMOSv10 (and comment out the line below it) #set clname "ProxyPass[virtual name]" set clname "::ProxyPass[virtual name]" # Initialize other local variables used in this rule set orig_uri "[HTTP::uri]" set orig_host "[HTTP::host]" set log_prefix "[virtual name], Host=$orig_host, URI=$orig_uri" set clientside "" set serverside "" set newpool "" set snataddr "" set ppass "" # TMOSv10: use this line for TMOSv10 (and comment out the line below it) # (don't forget to move the curly brace to the other line) #if {! [class exists $clname]} if {! [info exists $clname]} { # Data Group not defined: do not do anything further and exit this iRule log local0. "$log_prefix: Data Group $clname not found." pool $default_pool return } set match_len 0 if { $::ProxyPassDebug > 1 } { log local0. "$log_prefix: Looking for entries matching $orig_host$orig_uri" } # TMOSv10: use this line for TMOSv10 (and comment out the line below it) # (don't forget to move the curly brace to the other line) #foreach entry [class names $clname] foreach entry [set [set clname]] { # Look through data group to find an entry where the host/uri # starts with the clientside portion of an entry. Track the # length of the match to find the longest match (more specific). if {"$orig_host$orig_uri" starts_with [getfield $entry " " 1]} { set new_len [string length [getfield $entry " " 1]] if {$new_len > $match_len} { set ppass $entry set match_len $new_len } } } if {$ppass eq ""} { # We did not find an entry with the hostname, now try just the URI. # Look through data group to find an entry where the uri # starts with the clientside portion of an entry. Track the # length of the match to find the longest match (more specific). if { $::ProxyPassDebug > 1 } { log local0. "$log_prefix: Looking for entries matching $orig_uri" } # TMOSv10: use this line for TMOSv10 (and comment out the line below it) # (don't forget to move the curly brace to the other line) #foreach entry [class names $clname] foreach entry [set [set clname]] { if {$orig_uri starts_with [getfield $entry " " 1]} { set new_len [string length [getfield $entry " " 1]] if {$new_len > $match_len} { set ppass $entry set match_len $new_len } } } } if {$ppass eq ""} { # No entries found, stop processing this request if { $::ProxyPassDebug > 1 } { log local0. "$log_prefix: No rule found" } pool $default_pool return } # Store each entry in the data group line into a local variable set clientside [getfield $ppass " " 1] set serverside [getfield $ppass " " 2] set newpool [getfield $ppass " " 3] set snataddr [getfield $ppass " " 4] if {[substr $clientside 0 1] eq "/"} { # No virtual hostname specified, so use the Host header instead set host_clientside $orig_host set path_clientside $clientside } else { # Virtual host specified in entry, split the host and path set host_clientside [getfield $clientside "/" 1] set path_clientside [substr $clientside [string length $host_clientside]] } # At this point $host_clientside is the client hostname, and $path_clientside # is the client-side path as specified in the data group set host_serverside [getfield $serverside "/" 1] set path_serverside [substr $serverside [string length $host_serverside]] if {$host_serverside eq ""} { set host_serverside $host_clientside } # At this point $host_serverside is the server hostname, and $path_serverside # is the server-side path as specified in the data group # In order for directory redirects to work properly we have to be careful with slashes if {$path_clientside equals "/"} { # Make sure serverside path ends with / if clientside path is "/" if {!($path_serverside ends_with "/")} { append path_serverside "/" } } else { # Otherwise, neither can end in a / (unless serverside path is just "/") if {!($path_serverside equals "/")} { if {$path_serverside ends_with "/"} { set path_serverside [string trimright $path_serverside "/"] } if {$path_clientside ends_with "/"} { set path_clientside [string trimright $path_clientside "/"] } } } if { $::ProxyPassDebug > 0 } { log local0. "$log_prefix: Found Rule, Client Host=$host_clientside, Client Path=$path_clientside, Server Host=$host_serverside, Server Path=$path_serverside" } # As you may or may not know, if you go to http://www.domain.com/dir, and /dir is a directory, the web # server will redirect you to http://www.domain.com/dir/. The problem is, with ProxyPass, if the client-side # path is http://www.domain.com/dir, but the server-side path is http://www.domain.com/, the server will NOT # redirect the client (it isn't going to redirect you to http://www.domain.com//!). Here is the problem with # that. If there is an image referenced on the page, say logo.jpg, the client doesn't realize /dir is a directory # and as such it will try to load http://www.domain.com/logo.jpg and not http://www.domain.com/dir/logo.jpg. So # ProxyPass has to handle the redirect in this case. This only really matters if the server-side path is "/", # but since we have the code here we might as well offload all of the redirects that we can (that is whenever # the client path is exactly the client path specified in the data group but not "/"). if {$orig_uri eq $path_clientside} { if {[string index $path_clientside end] ne "/"} { set is_https 0 if {[PROFILE::exists clientssl] == 1} { set is_https 1 } # Assumption here is that the browser is hitting http://host/path which is a virtual path and we need to do the redirect for them if {$is_https == 1} { HTTP::redirect "https://$orig_host$orig_uri/" if { $::ProxyPassDebug } { log local0. "$log_prefix: Redirecting to https://$orig_host$orig_uri/" } } else { HTTP::redirect "http://$orig_host$orig_uri/" if { $::ProxyPassDebug } { log local0. "$log_prefix: Redirecting to http://$orig_host$orig_uri/" } } return } } # The following code does the actual rewrite on its way TO # the backend server. It replaces the URI with the newly # constructed one and masks the "Host" header with the FQDN # the backend pool server wants to see. # # If a new pool or custom SNAT are to be applied, these are # done here as well. If a SNAT is used, an X-Forwarded-For # header is attached to send the original requesting IP # through to the server. if {$host_clientside eq $orig_host} { if {$orig_uri starts_with $path_clientside} { # Do not bypass the iRule in the response set bypass 0 if { $::ProxyPassDebug > 1 } { log local0. "$log_prefix: New Host=$host_serverside, New Path=$path_serverside[substr $orig_uri [string length $path_clientside]]" } # Rewrite the URI HTTP::uri $path_serverside[substr $orig_uri [string length $path_clientside]] # Rewrite the Host header HTTP::header replace Host: $host_serverside # Now alter the Referer header if necessary if { [HTTP::header exists "Referer"] } { set protocol [substr [HTTP::header "Referer"] 0 $host_clientside] if {[string length $protocol] > 0} { set client_path [findstr [HTTP::header "Referer"] $host_clientside [string length $host_clientside]] if {$client_path starts_with $path_clientside} { if { $::ProxyPassDebug > 1 } { log local0. "$log_prefix: Changing Referer header: [HTTP::header Referer] with $protocol$host_serverside$path_serverside[substr $client_path [string length $path_clientside]]" } HTTP::header replace "Referer" $protocol$host_serverside$path_serverside[substr $client_path [string length $path_clientside]] } } } # Take care of pool selection and SNAT settings if {$newpool eq ""} { pool $default_pool if { $::ProxyPassDebug > 1 } { log local0. "$log_prefix: Using default pool $default_pool" } } else { pool $newpool if { $::ProxyPassDebug > 0 } { log local0. "$log_prefix: Using parsed pool $newpool" } } if {$snataddr != ""} { snat $snataddr if { $::ProxyPassDebug > 0 } { log local0. "$log_prefix: Using SNAT address $snataddr" } HTTP::header insert "X-Forwarded-For" "[IP::remote_addr]" } } } # If we're rewriting the response content, prevent the server from using # compression in its response by removing the Accept-Encoding header # from the request. LTM does not decompress response content before # applying the stream profile. This header is only removed if we're # rewriting response content. if { $::RewriteResponsePayload } { if { [HTTP::header exists "Accept-Encoding"] } { HTTP::header remove "Accept-Encoding" if { $::ProxyPassDebug > 1} { log local0. "$log_prefix: Removed Accept-Encoding header" } } } } when HTTP_RESPONSE { if {$bypass} { # No modification is necessary if we didn't change anything inbound # Check if we're rewriting the response if {$::RewriteResponsePayload} { if { $::ProxyPassDebug > 1 } { log local0. "$log_prefix: Rewriting response content enabled, but disabled on this response." } # Need to explicity disable the stream filter if it's not needed for this response # Hide the command from the iRule parser so it won't generate a validation error # when not using a stream profile set stream_disable_cmd "STREAM::disable" # Execute the STREAM::disable command. Use catch to handle any errors. Save the result to $result if { [catch {eval $stream_disable_cmd} result] } { # There was an error trying to disable the stream profile. log local0. "$log_prefix: Error disabling stream filter ($result). If you enable \$::RewriteResponsePayload, then you should add a stream profile to the VIP. Else, set \$::RewriteResponsePayload to 0 in this iRule." } } # Exit from this event. return } # Check if we're rewriting the response if {$::RewriteResponsePayload} { # Configure and enable the stream filter to rewrite the response payload # Hide the command from the iRule parser so it won't generate a validation error # when not using a stream profile if {$::RewriteResponsePayload > 1} { set stream_expression_cmd "STREAM::expression \"@$host_serverside$path_serverside@$host_clientside$path_clientside@ @$path_serverside@$path_clientside@\"" } else { set stream_expression_cmd "STREAM::expression \"@$host_serverside$path_serverside@$host_clientside$path_clientside@\"" } set stream_enable_cmd "STREAM::enable" if { $::ProxyPassDebug > 1 } { log local0. "$log_prefix: \$stream_expression_cmd: $stream_expression_cmd, \$stream_enable_cmd: $stream_enable_cmd" } # Execute the STREAM::expression command. Use catch to handle any errors. Save the result to $result if { [catch {eval $stream_expression_cmd} result] } { # There was an error trying to set the stream expression. log local0. "$log_prefix: Error setting stream expression ($result). If you enable \$::RewriteResponsePayload, then you should add a stream profile to the VIP. Else, set \$::RewriteResponsePayload to 0 in this iRule." } else { # No error setting the stream expression, so try to enable the stream filter # Execute the STREAM::enable command. Use catch to handle any errors. Save the result to $result if { [catch {eval $stream_enable_cmd} result] } { # There was an error trying to enable the stream filter. log local0. "$log_prefix: error enabling stream filter ($result): $result" } else { if { $::ProxyPassDebug > 1 } { log local0. "$log_prefix: Successfully configured and enabled stream filter" } } } } # Fix Location, Content-Location, and URI headers foreach header {"Location" "Content-Location" "URI"} { set protocol [substr [HTTP::header $header] 0 $host_serverside] if {$protocol ne ""} { set server_path [findstr [HTTP::header $header] $host_serverside [string length $host_serverside]] if {$server_path starts_with $path_serverside} { if { $::ProxyPassDebug } { log local0. "$log_prefix: Changing response header $header: [HTTP::header $header] with $protocol$host_clientside$path_clientside[substr $server_path [string length $path_serverside]]" } HTTP::header replace $header: $protocol$host_clientside$path_clientside[substr $server_path [string length $path_serverside]] } } } # Rewrite any domains/paths in Set-Cookie headers if {[HTTP::header exists "Set-Cookie"]}{ array set cookielist { } # A response may have multiple Set-Cookie headers, loop through them foreach cookievalue [HTTP::header values "Set-Cookie"] { set cookiename [getfield $cookievalue "=" 1] set newcookievalue "" # Each cookie starts with name=value and then has more name/value pairs foreach element [split $cookievalue ";"] { set element [string trim $element] if {$element contains "="} { set elementname [getfield $element "=" 1] set elementvalue [getfield $element "=" 2] if {$elementname eq "domain"} { # Rewrite domain of cookie, if necessary. if {$elementvalue eq $host_serverside} { if {$::ProxyPassDebug > 1} { log local0. "Modifying cookie $cookiename domain from $elementvalue to $host_clientside" } set elementvalue $host_clientside } } if {$elementname eq "path"} { # Rewrite path of cookie, if necessary. if {$elementvalue starts_with $path_serverside} { if {$::ProxyPassDebug > 1} { log local0. "Modifying cookie $cookiename path from $elementvalue to $path_clientside[substr $elementvalue [string length $path_serverside]]" } set elementvalue $path_clientside[substr $elementvalue [string length $path_serverside]] } } append newcookievalue "$elementname=$elementvalue; " } else { append newcookievalue "$element; " } } # Store new cookie value for later re-insertion. The cookie value # string will end with an extra "; " so strip that off here. set cookielist($cookiename) [string range $newcookievalue 0 [expr {[string length $newcookievalue] - 3}]] } # Remove all Set-Cookie headers and re-add them (modified or not) HTTP::header remove "Set-Cookie" foreach cookiename [array names cookielist] { HTTP::header insert "Set-Cookie" $cookielist($cookiename) if {$::ProxyPassDebug > 1} { log local0. "Inserting cookie: $cookielist($cookiename)" } } } } # Only uncomment this event if you need extra debugging for content rewriting. # This event can only be uncommented if the iRule is used with a stream profile. #when STREAM_MATCHED { # if { $::ProxyPassDebug } { # log local0. "$log_prefix: Rewriting match: [STREAM::match]" # } #} # The following code will look up SSL profile rules from # the Data Group List "ProxyPassSSLProfiles" and apply # them. # # The format of the entries in this list is as follows: # # # # All entries are separated by spaces, and both items # are required. Failure to set them will result in an # error message. when SERVER_CONNECTED { if {$bypass} { return } if {! [info exists ::ProxyPassSSLProfiles]} { return } set pool [LB::server pool] set profilename [findclass $pool ProxyPassSSLProfiles " "] if {$profilename eq ""} { if { [PROFILE::exists serverssl] == 1} { # Hide this command from the iRule parser (in case no serverssl profile is applied) set disable "SSL::disable serverside" catch {eval $disable} } return } if { $::ProxyPassDebug > 0 } { log local0. "$log_prefix: ServerSSL profile $profilename assigned for pool $pool" } if { [PROFILE::exists serverssl] == 1} { # Hide these commands from the iRule parser (in case no serverssl profile is applied) set profile "SSL::profile $profilename" catch {eval $profile} set enable "SSL::enable serverside" catch {eval $enable} } else { log local0. "$log_prefix: ServerSSL profile must be defined on virtual server to enable server-side encryption!" } } # ProxyPass Release History # v8.2: Jun 04, 2010: Fixed bug with directory slash logic # v8.1: May 15, 2009: Added internal redirects back in (removing them was a mistake) # v8.0: May 13, 2009: pulled in changes submitted by Aaron Hooley (hooleylists gmail com) # TMOS v10 support added. Cookie domain/path rewriting added. # v7.0: May 06, 2008: added optional serverssl contributed by Joel Moses # v6.0: Jan 15, 2008: Small efficiency change # v5.0: Jul 27, 2007: Added Referer header conversions # v4.0: Jul 27, 2007: Added optional debugging flag # v3.0: Jul 20, 2007: Added SNAT support contributed by Adam Auerbach # v2.0: May 28, 2007: Added internal directory redirects and optional stream profile # v1.0: Feb 20, 2007: Initial Release Tested this on version: 9.0546Views0likes0Comments