kk Blog —— 通用基础


date [-d @int|str] [+%s|"+%F %T"]
netstat -ltunp

nginx proxy_pass

https://www.cnblogs.com/xuey/p/9515996.html


nginx中有两个模块都有proxy_pass指令

ngx_http_proxy_module的proxy_pass

1
2
3
4
5
语法: proxy_pass URL;
场景: location, if in location, limit_except
说明: 设置后端代理服务器的协议(protocol)和地址(address),以及location中可以匹配的一个可选的URI。
	协议可以是"http"或"https"。地址可以是一个域名或ip地址和端口,或者一个 unix-domain socket 路径。  
详见官方文档: http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_pass

ngx_stream_proxy_module的proxy_pass

1
2
3
4
语法: proxy_pass address;
场景: server
说明: 设置后端代理服务器的地址。这个地址(address)可以是一个域名或ip地址和端口,或者一个 unix-domain socket路径。  
详见官方文档: http://nginx.org/en/docs/stream/ngx_stream_proxy_module.html#proxy_pass

两个proxy_pass的关系和区别

在两个模块中,两个proxy_pass都是用来做后端代理的指令。

ngx_stream_proxy_module模块的proxy_pass指令只能在server段使用使用, 只需要提供域名或ip地址和端口。可以理解为端口转发,可以是tcp端口,也可以是udp端口。 ngx_http_proxy_module模块的proxy_pass指令需要在location段,location中的if段,limit_except段中使用,处理需要提供域名或ip地址和端口外,还需要提供协议,如"http"或"https",还有一个可选的uri可以配置。

proxy_pass的具体用法

ngx_stream_proxy_module模块的proxy_pass指令

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
server {
  listen 127.0.0.1:12345;
  proxy_pass 127.0.0.1:8080;
}

server {
  listen 12345;
  proxy_connect_timeout 1s;
  proxy_timeout 1m;
  proxy_pass example.com:12345;
}

server {
  listen 53 udp;
  proxy_responses 1;
  proxy_timeout 20s;
  proxy_pass dns.example.com:53;
}

server {
  listen [::1]:12345;
  proxy_pass unix:/tmp/stream.socket; #设置源站地址
}

ngx_http_proxy_module模块的proxy_pass指令

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
server {
  listen    80;
  server_name www.test.com;

  # 正常代理,不修改后端url的
  location /some/path/ {
      proxy_pass http://127.0.0.1;
  }

  # 修改后端url地址的代理(本例后端地址中,最后带了一个斜线)
  location /testb {
      proxy_pass http://www.other.com:8801/;
  }

  # 使用 if in location
  location /google {
      if ( $geoip_country_code ~ (RU|CN) ) {
          proxy_pass http://www.google.hk;
      }
  }

  location /yongfu/ {
      # 没有匹配 limit_except 的,代理到 unix:/tmp/backend.socket:/uri/
      proxy_pass http://unix:/tmp/backend.socket:/uri/;

      # 匹配到请求方法为: PUT or DELETE, 代理到9080
      limit_except PUT DELETE {
          proxy_pass http://127.0.0.1:9080;
      }
  }

}

proxy_pass后端服务器的url(request_uri)情况分析

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
server {
  listen    80;
  server_name www.test.com;

  # 情形A
  # 访问 http://www.test.com/testa/aaaa
  # 后端的request_uri为: /testa/aaaa
  location ^~ /testa/ {
      proxy_pass http://127.0.0.1:8801;
  }
  
  # 情形B
  # 访问 http://www.test.com/testb/bbbb
  # 后端的request_uri为: /bbbb
  location ^~ /testb/ {
      proxy_pass http://127.0.0.1:8801/;
  }

  # 情形C
  # 下面这段location是正确的
  location ~ /testc {
      proxy_pass http://127.0.0.1:8801;
  }

  # 情形D
  # 下面这段location是错误的
  #
  # nginx -t 时,会报如下错误: 
  #
  # nginx: [emerg] "proxy_pass" cannot have URI part in location given by regular 
  # expression, or inside named location, or inside "if" statement, or inside 
  # "limit_except" block in /opt/app/nginx/conf/vhost/test.conf:17
  # 
  # 当location为正则表达式时,proxy_pass 不能包含URI部分。本例中包含了"/"
  location ~ /testd {
      proxy_pass http://127.0.0.1:8801/;   # 记住,location为正则表达式时,不能这样写!!!
  }

  # 情形E
  # 访问 http://www.test.com/ccc/bbbb
  # 后端的request_uri为: /aaa/ccc/bbbb
  location /ccc/ {
      proxy_pass http://127.0.0.1:8801/aaa$request_uri;
  }

  # 情形F
  # 访问 http://www.test.com/namea/ddd
  # 后端的request_uri为: /yongfu?namea=ddd
  location /namea/ {
      rewrite /namea/([^/]+) /yongfu?namea=$1 break;
      proxy_pass http://127.0.0.1:8801;
  }

  # 情形G
  # 访问 http://www.test.com/nameb/eee
  # 后端的request_uri为: /yongfu?nameb=eee
  location /nameb/ {
      rewrite /nameb/([^/]+) /yongfu?nameb=$1 break;
      proxy_pass http://127.0.0.1:8801/;
  }

  access_log /data/logs/www/www.test.com.log;
}

server {
  listen    8801;
  server_name www.test.com;
  
  root    /data/www/test;
  index   index.php index.html;

  rewrite ^(.*)$ /test.php?u=$1 last;

  location ~ \.php$ {
      try_files $uri =404;
      fastcgi_pass unix:/tmp/php-cgi.sock;
      fastcgi_index index.php;
      include fastcgi.conf;
  }

  access_log /data/logs/www/www.test.com.8801.log;
}

小结

情形A和情形B进行对比,可以知道proxy_pass后带一个URI,可以是斜杠(/)也可以是其他uri,对后端request_uri变量的影响。

情形D说明,当location为正则表达式时,proxy_pass不能包含URI部分(proxy_pass在以下情况下,指令中不能有URI,正则表达式位置、命名的地点、if 块),

情形E通过变量($request_uri, 也可以是其他变量),对后端的request_uri进行改写。

情形F和情形G通过rewrite配合break标志,对url进行改写,并改写后端的request_uri。需要注意,proxy_pass地址的URI部分在情形G中无效,不管如何设置,都会被忽略。

nginx https代理配置

https://segmentfault.com/a/1190000019563509


NGINX解决HTTPS代理的方式都属于透传(隧道)模式,即不解密不感知上层流量。具体的方式有如下7层和4层的两类解决方案。

HTTP CONNECT隧道 (7层解决方案)

客户端给代理服务器发送HTTP CONNECT请求。

代理服务器利用HTTP CONNECT请求中的主机和端口与目的服务器建立TCP连接。

代理服务器给客户端返回HTTP 200响应。

客户端和代理服务器建立起HTTP CONNECT隧道,HTTPS流量到达代理服务器后,直接通过TCP透传给远端目的服务器。代理服务器的角色是透传HTTPS流量,并不需要解密HTTPS。

NGINX ngx_http_proxy_connect_module模块

NGINX作为反向代理服务器,官方一直没有支持HTTP CONNECT方法。但是基于NGINX的模块化、可扩展性好的特性,阿里的@chobits提供了ngx_http_proxy_connect_module模块,来支持HTTP CONNECT方法,从而让NGINX可以扩展为正向代理。

NGINX stream (4层解决方案)

NGINX官方从1.9.0版本开始支持ngx_stream_core_module模块,模块默认不build,需要configure时加上 --with-stream 选项来开启。

ngx_stream_ssl_preread_module模块

要在不解密的情况下拿到HTTPS流量访问的域名,只有利用TLS/SSL握手的第一个Client Hello报文中的扩展地址SNI (Server Name Indication)来获取。NGINX官方从1.11.5版本开始支持利用ngx_stream_ssl_preread_module模块来获得这个能力,模块主要用于获取Client Hello报文中的SNI和ALPN信息。对于4层正向代理来说,从Client Hello报文中提取SNI的能力是至关重要的,否则NGINX stream的解决方案无法成立。同时这也带来了一个限制,要求所有客户端都需要在TLS/SSL握手中带上SNI字段,否则NGINX stream代理完全没办法知道客户端需要访问的目的域名。

1
2
3
4
5
6
7
8
9
stream {
	resolver 114.114.114.114;
	server {
		listen 443;
		ssl_preread on;
		proxy_connect_timeout 5s;
		proxy_pass $ssl_preread_server_name:$server_port;
	}
}

test

openssl带servername参数来指定SNI

1
openssl s_client -connect www.baidu.com:443 -servername www.baidu.com

nginx 代理配置

正向代理、反向代理 没有区别

客户端 —-> 代理服务器(发起访问请求) —-> 网站
客户端 <—- 代理服务器(响应的内容) <—- 网站

配置:(https 代理配置较麻烦)

ngx_http_proxy_module 代理配置:

1
2
3
4
5
6
7
8
9
10
11
server {
	listen 88;
	# resolver 8.8.8.8
	location / {
		proxy_pass $http_host$http_request_uri;
		# proxy_pass http://192.168.56.101:88; 多级代理的中间设备用这条

		# proxy_connect_timeout 600;
		# ...
	}
}

ngx_stream_proxy_module 代理配置:

NGINX官方从1.9.0版本开始支持ngx_stream_core_module模块,模块默认不build,需要configure时加上 --with-stream 选项来开启。

配置见 nginx https代理配置

squid 代理转发

https://www.cmdschool.org/archives/4673

Squid的层次结构

图中绿色线代表父子关系的层次结构(上游下游关系)

图中蓝色代表兄弟关系的层次结构(平等关系)

代理转发

Squid使用“cache_peer”指令提供父节点的缓存

cache_peer指令的模式

never direct模式,父节点失败不能直接连接源服务器,如果父节点失败或无法访问,则每个请求都导致错误消息

prefer direct模式,父节点失败允许直接连接源服务器,如果父节点失败或无法访问,则连接到源服务器而不是父节点

注:失败是指没有ICP或HTCP回复

never direct模式
1
2
cache_peer parentcache.foo.com parent 3128 0 no-query default
never_direct allow all

以上使用never_direct指令宣告父节点失败不能直接连接源服务器

prefer direct模式
1
2
3
cache_peer parentcache.foo.com parent 3128 0 no-query
prefer_direct off
nonhierarchical_direct off

以上使用prefer_direct指令宣告首选从DNS中列出源服务器尝试

以上使用nonhierarchical_direct指令宣告往父节点的请求继续发送

hierarchy_stoplist指令是prefer direct模式的另外一种实现(适用于Squid-3.2之前的版本)

cache_peer指令的使用
1
cache_peer hostname type http-port icp-port [options]

hostname参数,指定转发的代理服务器主机名称(IP地址亦可)

type参数,可选值有“parent”(父母)、“sibling”(兄弟)和“multicast”(多播)

http-port参数,指定转发的代理服务器通讯端口,默认值3128

icp-port参数,查询对象的邻居缓存,如果不支持ICP或HTCP,设置为0

options参数,可选的其他选项(不一一列举)

http://www.squid-cache.org/Doc/config/cache_peer/

KASLR 内核动态地址

/proc/kallsyms 和 /boot/System.map-xxx 一致需要修改 .config

1
2
3
4
5
6
< # CONFIG_RANDOMIZE_BASE is not set
---
> CONFIG_RANDOMIZE_BASE=y
> CONFIG_X86_NEED_RELOCS=y
> CONFIG_RANDOMIZE_MEMORY=y
> CONFIG_RANDOMIZE_MEMORY_PHYSICAL_PADDING=0xa

http://www.wowotech.net/memory_management/441.html

引言

什么是KASLR?KASLR是kernel address space layout randomization的缩写,直译过来就是内核地址空间布局随机化。KASLR技术允许kernel image加载到VMALLOC区域的任何位置。当KASLR关闭的时候,kernel image都会映射到一个固定的链接地址。对于黑客来说是透明的,因此安全性得不到保证。KASLR技术可以让kernel image映射的地址相对于链接地址有个偏移。偏移地址可以通过dts设置。如果bootloader支持每次开机随机生成偏移数值,那么可以做到每次开机kernel image映射的虚拟地址都不一样。因此,对于开启KASLR的kernel来说,不同的产品的kernel image映射的地址几乎都不一样。因此在安全性上有一定的提升。

注:文章代码分析基于linux-4.15,架构基于aarch64(ARM64)。

如何使用

打开KASLR功能非常简单,在支持KASLR的内核配置选项添加选项CONFIG_RANDOMIZE_BASE=y。同时还需要告知kernel映射的偏移地址,通过dts传递。在chosen节点下添加kaslr-seed属性。属性值就是偏移地址。另外command line不要带nokaslr,否则KASLR还是关闭。dts信息举例如下。顺便说一下,在dts中<>符号中是一个32 bit的值。但是在ARM64平台,这里的kaslr-seed属性是一个特例,他就是一个64 bit的值。

1
2
3
4
5
/ {
	chosen {
		kaslr-seed = <0x10000000>;
	};
}; 

如何获取偏移

kaslr-seed属性的解析在kaslr_early_init函数完成。该函数根据输入参数dtb首地址(物理地址)解析dtb,找到偏移地址,最后返回。kaslr_early_init实现如下。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
u64 __init kaslr_early_init(u64 dt_phys)
{
	void *fdt;
	u64 seed, offset, mask, module_range;
	const u8 *cmdline, *str;
	int size;
 
	early_fixmap_init();                                         /* 1 */
	fdt = __fixmap_remap_fdt(dt_phys, &size, PAGE_KERNEL);       /* 1 */
 
	seed = get_kaslr_seed(fdt);                                  /* 2 */
	if (!seed)
		return 0;
 
	cmdline = get_cmdline(fdt);
	str = strstr(cmdline, "nokaslr");                            /* 3 */
	if (str == cmdline || (str > cmdline && *(str - 1) == ' '))
		return 0;
 
	mask = ((1UL << (VA_BITS - 2)) - 1) & ~(SZ_2M - 1);          /* 4 */
	offset = seed & mask;
 
	/* use the top 16 bits to randomize the linear region */
	memstart_offset_seed = seed >> 48;                           /* 5 */
 
	if ((((u64)_text + offset) >> SWAPPER_TABLE_SHIFT) !=
		(((u64)_end + offset) >> SWAPPER_TABLE_SHIFT))
		offset = round_down(offset, 1 << SWAPPER_TABLE_SHIFT);   /* 6 */
 
	return offset;
} 

由于dtb的地址是物理地址,因此第一步先为dtb区域建立映射。
从dtb文件获取kaslr-seed属性的值。
确保command line没有传递nokaslr参数,如果传递nokaslr则关闭KASLR。
保证传递的偏移地址2M地址对齐,并且保证kernel位于VMALLOC区域大小的一半地址空间以下 (VA_BITS - 2)。当VA_BITS=48时,mask=0x0000_3fff_ffe0_0000。
线性映射区地址也会随机化。
kernel启动初期只有一个PUD页表,因此希望kernel映射在1G(1 << SWAPPER_TABLE_SHIFT)大小范围内,这样就不用两个PUD页表。如果kernel加上偏移offset后不满足这点,自然要重新对齐。

如何创建映射

kernel启动初期在汇编阶段创建映射关系。代码位于head.S文件。在__primary_switched函数中会调用kaslr_early_init得到偏移地址。保存在x23寄存器中。然后重新创建kernel image的映射。

1
2
3
4
5
6
7
8
9
__primary_switched:
	tst   x23, ~(MIN_KIMG_ALIGN - 1)  // already running randomized?
	b.ne  0f
	mov   x0, x21                     // pass FDT address in x0
	bl    kaslr_early_init            // parse FDT for KASLR options
	cbz   x0, 0f                      // KASLR disabled? just proceed
	orr   x23, x23, x0                // record KASLR offset
	ldp   x29, x30, [sp], #16         // we must enable KASLR, return
	ret                               // to __primary_switch() 

创建映射的函数是__create_page_tables

1
2
3
4
5
6
7
8
9
10
11
12
13
__create_page_tables:
	/*
	 * Map the kernel image.
	 */
	adrp  x0, swapper_pg_dir
	mov_q x5, KIMAGE_VADDR + TEXT_OFFSET  // compile time __va(_text)
	add   x5, x5, x23                         // add KASLR displacement
	create_pgd_entry x0, x5, x3, x6
	adrp  x6, _end                        // runtime __pa(_end)
	adrp  x3, _text                       // runtime __pa(_text)
	sub   x6, x6, x3                          // _end - _text
	add   x6, x6, x5                          // runtime __va(_end)
	create_block_map x0, x7, x3, x5, x6

这段代码在我的另一篇文章《ARM64 Kernel Image Mapping的变化》已经有分析过,这里就略过了。注意第7行,kernel image映射的虚拟地址加上了一个偏移地址x23。还有一点需要说明,就是对重定位段进行重定位。这部分代码在arch/arm64/kernel/head.S文件__relocate_kernel函数实现。大概说下__relocate_kernel有什么用呢!例如链接脚本中常见的几个变量text、etext、end。这几个你应该很熟悉,他们是一个地址并且他们的值是链接的时候确定下来,那么现在使能kaslr的情况下,代码中再访问text的值就很明显不是运行时的虚拟地址,而是链接时候的值。因此,__relocate_kernel函数可以负责重定位这些变量。保证访问这些变量的值依然是正确的值。这部分涉及编译和链接,有兴趣的可以研究一下《程序员的自我修养》这本书(我不太熟悉)。

addr2line怎么办

KASLR在技术上增加了OS安全性,但是对于调试或许增加了些难度。何以见得呢?首先,我们知道编译kernel的时候链接地址和最终运行地址是不一样的,因此如果发生oops,栈的回溯信息中的函数地址其实都是运行地址。如果你使用过addr2line工具的话,应该不会陌生addr2line -e vmlinux 0xffffff8000080000这条命令获取某个地址在代码中的哪一行。那么现在问题是oops中的地址和链接地址有一个偏差,并且这个偏差随着bootloader传递的值而变化。现在摆在我们眼前的是addr2line工具还怎么用?下面就为你答疑解惑。kernel开机log中会打印Virtual kernel memory layout。举例如下。

    Virtual kernel memory layout:
      modules : 0xffffff8000000000 - 0xffffff8008000000   (   128 MB)
      vmalloc : 0xffffff8008000000 - 0xffffffbebfff0000   (   250 GB)
        .text : 0xffffff80ae280000 - 0xffffff80af2e0000   ( 16768 KB)
      .rodata : 0xffffff80af300000 - 0xffffff80afb60000   (  8576 KB)
        .init : 0xffffff80afb60000 - 0xffffff80b01e0000   (  6656 KB)
        .data : 0xffffff80b01e0000 - 0xffffff80b044f200   (  2493 KB)
         .bss : 0xffffff80b044f200 - 0xffffff80b0e18538   ( 10021 KB)
      fixed   : 0xffffffbefe7fb000 - 0xffffffbefec00000   (  4116 KB)
      PCI I/O : 0xffffffbefee00000 - 0xffffffbeffe00000   (    16 MB)
      vmemmap : 0xffffffbf00000000 - 0xffffffc000000000   (     4 GB maximum)
            0xffffffbf00000000 - 0xffffffbf03000000   (    48 MB actual)
      memory  : 0xffffffc000000000 - 0xffffffc0c0000000   (  3072 MB)

注意看以上.text区域(kernel代码段)起始地址和结束地址是不是位于VMALLOC区域。如果发生oops,log中函数的地址必然是一个位于.text段的地址,假设是addr_run,但是链接地址应该是KIMAGE_VADDR + TEXT_OFFSET,这两个宏定义参考这篇文章《ARM64 Kernel Image Mapping的变化》。在这个例子中,KIMAGE_VADDR = 0xffffff8008000000,TEXT_OFFSET = 0x80000。addr2line工具使用的必须是链接地址,因此需要将addr_run转换成链接地址。公式很容易推导出来,addr_link = addr_run - .text_start + vmalloc_start + TEXT_OFFSET。在这个例子中就是addr_link = addr_run - 0xffffff80ae280000 + 0xffffff8008000000 + 0x80000。计算的addr_link就可以使用addr2line工具解析了。Have fun!