ict.ken.be

 

Posts in Category: Network

HTTP Fundamentals - Notes 

Categories: Network Notes

by Scott Allen

  • HTTP: HyperText Transfer Protocol
  • URL: Uniform Resource Locator

urlScheme://host:port/urlPath?q=query#fragment

URL Encoding
Safe Characters: a-z A-Z 0-9 $-_.+*'(),

Common MIME Types

  • Type/Subtype
  • application/atom+xml
  • application/json
  • image/gif
  • image/png
  • video/mp4
  • text/xml
  • text/html
  • text/plain

Content Negotiation

html: http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4
date: http://tools.ietf.org/html/rfc822#section-5.1

HTTP Transaction: HTTP Request + HTTP Response

telnet odetocode.com 80
GET /odetocode.jpg HTTP/1.1
Host: www.odetocode.com
enter key twice

HTTP Request Methods
GET, POST, PUT, DELETE, HEAD
Safe versus Unsafe: http://en.wikipedia.org/wiki/Post/Redirect/Get

Request Message
[method] [URL] [version]
[headers]
[body]

GET / HTTP/1.1
Host: server.com
Connection: keep-alive
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language:fr-FR
Accept-Encoding: gzip,deflate,sdch
Date: Fri, 9 Aug 2002 21:12:00 GMT
Referer, User-Agent, Accept, Cookie, If-Modified-Since, Accept-Charset

The default q value is 1.0 preference of accept

Response Message
[version] [status] [reason]
[headers]
[body]

HTTP/1.1 200 OK
Cache-Control: private
Content-Type: text/html; charset=utf-8
X-headers are reserved for nonstandard headers

301 permanent do not come here again
302 temporarly eg. redirect after sign-in

TCP: Transmision Control Protocol -> Reliable (Transport)
not UDP: User Datagram Protocol -> Unreliable
Opens a socket on IP
IP: Internet Protocol (Network)
Ethernet (Data Link)

private static string GetResource(Uri uri)
{
var hostEntry = Dns.GetHostEntry(host);
var socket = CreateSocket(uri.hostEntry);
SendRequest(socket, uri.Host, uri.PathAndQuery);
return GetResponse(socket);
}

private static Socket CreateSocket(IPHostEntry hostEntry)
{
const int httpPort = 80;
var endPoint = new IPEndPoint(hostEntry.AddressList[0], httpPort);
var socket = new Socket(endPoint.AddressFamily, SocketType.Stream, Protocol.Tcp);
socket.Connect(endPoint);
if (socket.Connected) return socket;
return null;
}

private static void SendRequest(Socket socket, string host, string resource)
{
var requestMessage = String.Format(
"GET {0} HTTP/1.1\r\n" +
"Host: {1}\r\n" +
"\r\n", resource, host
);
var requestBytes = Encoding.ASCII.GetBytes(requestMessage);
socket.Send(requestBytes);
}
private static string GetResponse(Socket socket)
{
int bytes = 0;
byte[] buffer = new byte[256];
var result = new StringBuilder();
do
{
bytes = socket.Receive(buffer);
result.Append(Encoding.ASCII.GetString(buffer, 0, bytes));
}
return result.ToString();
}

http://wireshark.org
Capture Options
Capture Filter: host odetocode.com
3 step TCP Handshake

www.ietf.org/rfs/rfc2616.txt
A single-user client SHOULD NOT maintain more than 2 connections with any server or proxy.

http://en.wikipedia.org/wiki/Slow-start

Default connection close about 5 seconds.
Shared hosts often send 'Connection: close' in header to allow more connections.

HTTP Architecture

http://odata.netflix.com/v2/Catalog/ (https://hidemyass.com/)
REST: www.ics.uci.edu/~fielding/pubs/dissertation/top.htm
Forward Proxy: using a proxy as an access control device (by dropping messages)
Reverse Proxy: eg. loadbalancer
Fiddler installs itself as a local 127.0.0.1:8888 proxy in your browser

Caching
Chrome: about:cache

Cache It: HTTP/1.1 200 OK GET
Don't cache: PUT, POST, DELETE

Cache-Control: private, max-age=0
Expires: ... should no longer be used
Pragma: ... should no longer be used

Cache Control

  • public: A response for everyone
  • private: A response for a single user
  • no-cache, must-revalidate: Don't cache the response
  • no-store: You never saw this response
Response.Cache.SetCacheability(HttpCacheability.Public);
Response.Cache.SetExpires(DateTime.Now.AddSeconds(60));

If-Modified-Since: Wed, 14 Sep 2011 19:02:18 GMT

Etag: "07f2a22ffd9cc1:0" hash of the resource
If-None-Match: "07f2a22ffd9cc1:0"

HTTP Security
Cookies and Authentication
http://tools.ietf.org/html/rfc6265
About 4kb max

Saving State
ViewState <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/foo" />
Store in database
SessionState Store
Cookies

Set-Cookie: ASP.NET_SessionId=foo; path=/; HttpOnly

domain=.searchengine.com (include subdomains)
expires=Monday, 09-July-2012 21:12:00 GMT

Security

Basic Authentication
WWW-Authenticate: Basic realm="localhost"
Authorization: Basic base64encodedusernameandpassword

Digest Authentication
WWW-Authenticate: Digest realm="localhost", qop="auth,auth-int", nonce="...", opaque="..."

Windows Authentication
WWW-Authenticate: Negotiate
NTLM and Kerberos

Forms Authentication
Location: /login?ReturnUrl=/account

OpenID: Google, Yahoo, myOpenId, StackExchange, facebook

HTTPS
Adds a SSL/TLS layer inbetween application and transport layer
Certificate with Public/Private key
Everything except the hostname

Http status codes explained 

Categories: Network WebApi

Funny way to finally remember all of these, the boring text version of http status codes you can find here.

Http status codes explained with pictures

1xx Informational

  • 100 Continue
  • 101 Switching Protocols

2xx Successful

  • 200 OK : should be used to indicate a non-specific success
  • 201 Created : must be used to indicate successful resource creation
  • 202 Accepted : must be used to indicate a succesful start of an asynchronous action and should only be send by controllers
  • 203 Non-Authoritative Information
  • 204 No Content : should be used when the response body is intentionally empty
  • 205 Reset Content
  • 206 Partial Content

3xx Redirection

  • 300 Multiple Choices
  • 301 Moved Permanently : should be used to relocate resources
  • 302 Found : should only redirect automatically when it was a get or head request
  • 303 See Other : should be used to refer the client to a different uri, so sending a reference to a client without forcing it to download it's state
  • 304 Not Modified : should be used to preserve bandwidth and the response body must be empty
  • 305 Use Proxy
  • 306 (Unused)
  • 307 Temporary Redirect : should be used to tell clients to resubmit the request to another uri
  • 308 Permanent Redirect : does not allow to change the method

4xx Client Error

  • 400 Bad Request : may be used to indicate non-specific failure
  • 401 Unauthorized : must be used when there is a problem with the clients credentials
  • 402 Payment Required
  • 403 Forbidden : should be used to forbid access regardless of authorization state, so for any requests outside the clients permitted scope
  • 404 Not Found : must be used when a client uri cannnot be mapped to a resource
  • 405 Method Not Allowed : must be used when the http method is not supported, for example using a PUT on a read-only resource (must include the allow header in response)
  • 406 Not Acceptable : must be used when requested media type cannot be served (accept request header)
  • 407 Proxy Authentication Required
  • 408 Request Timeout
  • 409 Conflict : should be used to indicate a violation of resource state, for example a client tries to delete a non empty store
  • 410 Gone
  • 411 Length Required
  • 412 Precondition Failed
  • 413 Request Entity Too Large
  • 414 Request-URI Too Long
  • 415 Unsupported Media Type : must be used when the media type of a requests payload cannot be processed (content type header)
  • 416 Requested Range Not Satisfiable
  • 417 Expectation Failed
  • 418 I'm a teapot (RFC 2324)
  • 419 Authentication Timeout
  • 420 Enhance Your Calm (use 429 instead)
  • 421 Bad mapping
  • 422 Unprocessable Entity
  • 423 Locked
  • 424 Failed Dependency
  • 425 Unordered Collection
  • 426 Upgrade Required
  • 427 Soap action required (in case your api is dirty)
  • 428 Precondition Required (RFC 6585)
  • 429 Too Many Requests (RFC 6585)
  • 430 (not used ?? sometimes misused for 431)
  • 431 Request Header Fields Too Large (RFC 6585)

5xx Server Error

  • 500 Internal Server Error
  • 501 Not Implemented
  • 502 Bad Gateway
  • 503 Service Unavailable
  • 504 Gateway Timeout
  • 505 HTTP Version Not Supported

5xx Server Error

  • 500 Internal Server Error
  • 501 Not Implemented
  • 502 Bad Gateway
  • 503 Service Unavailable
  • 504 Gateway Timeout
  • 505 HTTP Version Not Supported
  • 520 Origin Error
  • 521 Web server is down
  • 522 Connection timed out
  • 523 Proxy Declined Request
  • 524 A timeout occured

7xx Developer Error

  • 70x - Inexcusable
  • 701 - Meh
  • 702 - Emacs
  • 703 - Explosion
  • 704 - Goto Fail
  • 705 - I wrote the code and missed the necessary validation by an oversight (see 795)
  • 71x - Novelty Implementations
  • 710 - PHP
  • 711 - Convenience Store
  • 712 - NoSQL
  • 719 - I am not a teapot
  • 72x - Edge Cases
  • 720 - Unpossible
  • 721 - Known Unknowns
  • 722 - Unknown Unknowns
  • 723 - Tricky
  • 724 - This line should be unreachable
  • 725 - It works on my machine
  • 726 - It's a feature, not a bug
  • 727 - 32 bits is plenty
  • 73x - F*cking
  • 731 - F*cking Rubygems
  • 732 - F*cking Unicđź’©de
  • 733 - F*cking Deadlocks
  • 734 - F*cking Deferreds
  • 735 - F*cking IE
  • 736 - F*cking Race Conditions
  • 737 - F*ckThreadsing
  • 738 - F*cking Bundler
  • 739 - F*cking Windows
  • 74x - Meme Driven
  • 740 - Computer says no
  • 741 - Compiling
  • 742 - A kitten dies
  • 743 - I thought I knew regular expressions
  • 744 - Y U NO write integration tests?
  • 745 - I don't always test my code, but when I do I do it in production
  • 746 - Missed Ballmer Peak
  • 747 - Motherf*cking Snakes on the Motherf*cking Plane
  • 748 - Confounded by Ponies
  • 749 - Reserved for Chuck Norris
  • 75x - Syntax Errors
  • 750 - Didn't bother to compile it
  • 753 - Syntax Error
  • 754 - Too many semi-colons
  • 755 - Not enough semi-colons
  • 756 - Insufficiently polite
  • 757 - Excessively polite
  • 759 - Unexpected T_PAAMAYIM_NEKUDOTAYIM
  • 76x - Substance-Affected Developer
  • 761 - Hungover
  • 762 - Stoned
  • 763 - Under-Caffeinated
  • 764 - Over-Caffeinated
  • 765 - Railscamp
  • 766 - Sober
  • 767 - Drunk
  • 768 - Accidentally Took Sleeping Pills Instead Of Migraine Pills During Crunch Week
  • 769 - Questionable Maturity Level
  • 77x - Predictable Problems
  • 771 - Cached for too long
  • 772 - Not cached long enough
  • 773 - Not cached at all
  • 774 - Why was this cached?
  • 776 - Error on the Exception
  • 777 - Coincidence
  • 778 - Off By One Error
  • 779 - Off By Too Many To Count Error
  • 78x - Somebody Else's Problem
  • 780 - Project owner not responding
  • 781 - Operations
  • 782 - QA
  • 783 - It was a customer request, honestly
  • 784 - Management, obviously
  • 785 - TPS Cover Sheet not attached
  • 786 - Try it now
  • 787 - Further Funding Required
  • 79x - Internet crashed
  • 791 - The Internet shut down due to copyright restrictions.
  • 792 - Climate change driven catastrophic weather event
  • 793 - Zombie Apocalypse
  • 794 - Someone let PG near a REPL
  • 795 - #heartbleed (see 705)
  • 797 - This is the last page of the Internet. Go back
  • 799 - End of the world

Still need more?

TCP/IP Networking for Developers - Notes 

Categories: Network Notes
TCP/IP Networking for Developers
Steve Evans - http://sevans.info
This was by far the worst Pluralsight tutorial I have ever seen, I am not an expert in networking and had hoped to learn a thing or two. Unfortunately, the course was not only very unstructured but also not very enlighting. Not even for a computer noob.
 
  • ipconfig
  • ipconfig /all | more
  • ipconfig /displaydns

  • c:\windows\system32\drivers\etc\hosts
  • You can put multiple hostnames on one line
  • 127.0.0.1 ken.be patrycja.pl test.be

  • No DHCP then 169.254.x.x

 

  • Change your ip logging to ipV6
 
Name resolution
  • nslookup ken.be
  • nslookup + enter, server 8.8.4.4
 
  • a-record transforms hostname into ip
  • set type=NS (nameserver)
  • set type=MX (mailexchange)
  • set type=CN (canonicalname or alias)
  • set type=AAAA (quad a) returns ipv6
  • wildcards records
 
A router connects different subnets
  • tracert
  • pathping
 

subnets

  • 255.255.255.node
  • 255.255.node
  • 255.255.255.240
 

routes

  • 0.0.0.0 means any ip address (netmask 0.0.0.0 to gateway)
  • 127.anything is always the localhost (netmask 255.0.0.0)
  • gateway.0 all that are on-link
  • 255.255.255.255 broadcast that doesn't cross router
  • route print
 
NAT (Network Address Translation)
  • Private Network Ranges
  • 10.0.0.0/255.0.0.0
  • 172.16.0.0/255.240.0.0
  • 192.168.0.0/255.255.0.0
 
Port Connectivity
  • TCP (Transmision Control Protocol) - request missing
  • UDP (User Datagram Protocol) - no check if received - no session
 
  • telnet ken.be 80
  • 400 Bad Request
  • port 1433 standard mssql
  • port 25 smtp
 
  • nmap -v servername (zenmap is win gui)
  • netstat -ano
 
Windows firewall
  • Log dropped packets
 
ICMPv4 protocol used by ping
Network Capture
Wireshark : right-click and follow tcp stream
Fiddler
 

 

Web Pro Series by Scott Forsyth 

Categories: IIS Network

These are some notes from the 'Web Pro Series' by Scott Forsyth. The series is a good start for IIS developers.

Forever Penguin

  • most big sites you can't ping, to limit DoS attacks
  • ping www.google.com -t

Tracert

  • Tracert sends an ICMP echo packet, but it takes advantage of the fact that most Internet routers will send back an ICMP 'TTL expired in transit' message if the TTL field is ever decremented to zero by a router.

DNS

  • Primary zone authoritavie answer
  • Host or A-record
  • Alias or CName
  • Mail or MX (lower number is higher priority, same priority then load balance)
  • TXT mainly used for SPF
  • * wildcard has lowest priority

NsLookup

  • set type=ns
  • set type=mx
  • set type=a
  • set type=ptr
  • + yourdomain.com.
  • server
  • lserver
  • ls (mostly zone transfers no longer allowed)

Cmd Capturing

  • dir /od | clip (copy to clipboard)
  • ipconfig /all > ipconfig.txt (use >> to append to the file)
  • echo "--- end ---" >> ipconfig.txt 
  • copy and paste : properties - enable QuickEdit mode

IIS Bindings

  • Type can be left blank
  • All assigned is a wildcard
  • You can specify the ip manually
  • Port must be specified
  • Hostname left blank will catch everything

SSL Bindings

  • Hostheader lives at application layer, so can not know before decryption
  • Assign a dedicated ip for each website that needs ssl
  • If sharing ip, you must share cert (only one cert per IP)
  • Wildcard certificate
  • Unified Communications Certificate (SAN)
    • Certificates - Computer Account - Local - Properties - Friendlyname put * in front - Hostname will be selectable
    • Select one site as master binding - system32\inetsrv\appcmd set site /site.name:"<SiteName>" /+bindings.[protocol='https',bindinginformation='*:443:<HostHeader>']
    • eg. appcmd set site /site.name:"ict.ken.be" /+bindings.[protocol='https',bindinginformation='10.240.5.22:443:ict.ken.be']
    • Prevent non-https to goto wrong https - On Master - Edit Inbound Rule - Matches the Pattern - .* - Match All - HTTP_HOST Does Not Match the Pattern - ^ict\.ken\.be& - Abort Request

URL Rewrite

  • iis.net - download url rewrite module
<configuration>
<system.webServer>
<rules>
<rule name="Redirect to google">
<match url=".*" />
<action type="None" />
</rule>
</rules>
</system.webServer>
</configuration>
  • global level vs site level
  • {HTTP_HOST} - Matches Regular Expression - ^ken\.be$
  • {REMOTE_HOST} - eg. allow only one specific ip
  • Edit Inbound Rule - login\.aspx$ - {HTTP_HOST} - ^ict\.ken\.be$ - {HTTPS} off - redirect https://ict.ken.be/{R:0}

Regex

  • http://www.ultrapico.com/expresso.htm
  • http://regexlib.com
 ^ start 
$ end
. any single char (not line breaks like \r & \n)
\ to escape special characters
.+ 1 or more
.* 0 or more
| or
? optional
() to create section for back references
(^&) anything but a &
[] character class
/w alphanumeric
/d digit
{n} repeat n times
{R:0} backreference to url
{C:0} backreference to condition

AppDomain will be recycled when

  • iis settings that affect application pool
  • web.config changes (notepad ctrl-s is enough, no need for change)
  • App_* are touched 
  • bin folder is touched
  • adding a folder
  • change the default document order (changes web.config)
  • web.config or machine.config in .Net framework folder
  • not when changing applicationHost.config (system32\inetsrv\config\applicationHost.config)

IIS Outbound Rules

  • update pages and headers on the way out
  • rewrite outbound rule
  • (.*)google\.com(.*) -> {R:1}bing.com{R:2}
  • not possible for static compression
  • Server Variable: RESPONSE_X_Server_Name -> Your domain name is {HTTP_HOST}

IIS Folders

  • Normal folder
  • Application folder (separate bounderies)
  • vDir Only Folder (when folder has different physical location)
  • vDir with Application

Overlapping App Pools (90 seconds)

  • w3wp.exe
  • appcmd list wp
  • http.sys -> w3wp.exe

IIS 7 - Configuration System

redirection.config -> applicationHost.config -> administration.config -> web.config (site) -> web.config (app)
machine.config -> web.config (root) -> web.config (site) -> web.config (app) -> web.config (subfolders)

c:\windows\system32\inetsrv\config

  • Anything on read/write in feature delegation can be changed through the web.config (also for remote configuration)
  • You can see in the statusbar if web.config will be changed.
  • SSL is not delegated by default.

Gotcha's:

  • Easy to overwrite settings
  • AppDomain recycle on change of web.config
  • Configuration is 'all over the place'
  • Not replicated with shared config

applicationHost.config Editing

  • <applicationPools>
  • <sites>
  • <system.webServer>
  • <webFarms>
  • <location>

IIS Schemas: c:\windows\system32\inetsrv\config\schema

Process Monitor: http://www.sysinternals.com

IUSR is used for anonymous access, unless you set it on the pool.

IIS Runtime page requests

  • rsca
  • Worker Processes - Running Pools - Click - View Current Requests
  • appcmd /?
  • appcmd list request /?
  • appcmd list request | clip
  • appcmd list request /site.name:foo.com /eleapsed:5000

Application Pools Identity

  • Remove users for file permissions
  • iis apppool\foo.com (virtual account)
  • Object Types - Make sure built-in security is checked

for iis 7 : icacls c:\inetpub\wwwroot /grant "iis apppool\foo.com":(IO)(IO)(RX)

  • network service controls the iis apppool user
  • User mapping is done by the AppHostSvc on creation.
  • Use custom user when the account needs network access.

Securing IIS

  • LocalService
  • LocalSystem
  • NetworkService
  • ApplicationPoolIdentity (no password needed)
  • Custom Account, no need to add to a group.

Disk Permissions:

  • No need for inheritance, creator owner, users, trustedinstaller.
  • So we have SYSTEM, ADMINISTRATOR and CUSTOM USER
  • Prefer local user to a domain user.

Website - Authentication - Anonymous Access - Set on pool if all individual pools

Web Gardens

Maximum Worker Process defaults to 1 (no garden)

pro

  • Remove contention with concurrent requests
  • PHP ISAPI Mode may benefit (or com+) -> move to FastCGI
  • Troubleshooting measure

con

  • In-proc session state won't work
  • Shared memory/cache is duplicated
  • First hit per worker process
  • Base memory adds up
  • More processes to monitor

There is no real need to use web gardens.

Better performance tuning: http://support.microsoft.com/kb/821268

IP restrictions with URL rewrite

Old fashion way:
IP Address and Domain restrictions feautre.
Add Allow Range - 10.240.0.0 - 255.255.0.0
Feature by default deny

New for example for staging:
eg. <% If Request("HTTP_HOST") = "staging.contoso.com" %>...<% End If %>

(only static rules)
Url Rewrite at global level
Add Rewrite Map - Authorized Admin IP - Add Mapping Entry - Some IP + New Value = 1
If Add Rule - Flag Authorized Admins - Pattern * - {Authorized Admin IP:{REMOTE_ADDR}} - Matches Pattern - 1
Then sdd server variable HTTP_X_AUTHORIZED_ADMIN - yes
Action Type - None
Add Rule - Block unauthorized users
{HTTP_HOST} - Matches - ^staging\..*
{HTTP_X_AUTHORIZED_ADMIN} - Not Match - yes
Custom Response 403 Forbidden

Page 3 of 3 << < 1 2 3