# 資訊 :::info - Question: Two Sum - From: picoCTF Binary Exploitation - Difficulty: 100 points ::: --- # 目錄 :::info [TOC] ::: --- # 題目 > `n1` > `n1` + `n2` OR `n2` > `n1` + `n2` > What two positive numbers can make this possible? ```C= #include <stdio.h> #include <stdlib.h> static int addIntOvf(int result, int a, int b) { result = a + b; if(a > 0 && b > 0 && result < 0) return -1; if(a < 0 && b < 0 && result > 0) return -1; return 0; } int main() { int num1, num2, sum; FILE *flag; char c; printf("n1 > n1 + n2 OR n2 > n1 + n2 \n"); fflush(stdout); printf("What two positive numbers can make this possible: \n"); fflush(stdout); if (scanf("%d", &num1) && scanf("%d", &num2)) { printf("You entered %d and %d\n", num1, num2); fflush(stdout); sum = num1 + num2; if (addIntOvf(sum, num1, num2) == 0) { printf("No overflow\n"); fflush(stdout); exit(0); } else if (addIntOvf(sum, num1, num2) == -1) { printf("You have an integer overflow\n"); fflush(stdout); } if (num1 > 0 || num2 > 0) { flag = fopen("flag.txt","r"); if(flag == NULL){ printf("flag not found: please run this on the server\n"); fflush(stdout); exit(0); } char buf[60]; fgets(buf, 59, flag); printf("YOUR FLAG IS: %s\n", buf); fflush(stdout); exit(0); } } return 0; } ``` # 解法 從題目可以看出來,題目要我們找到兩個數字滿足 `n1` > `n1` + `n2` OR `n2` > `n1` + `n2` 這個情況,就會給我 flag 從原始碼驗證一下,直接看 main function,如果在 27 行的 if 判斷沒有辦法跳到 else 那邊,基本上就沒機會拿到 flag,而要跳到 else 的條件就是讓 `addIntOvf(sum, num1, num2) == -1` 成立 來看看 `addIntOvf(sum, num1, num2)` 怎麼運作的,第 4 行有說到如果可以輸入兩個整數 num1 和 num2,如果讓 num1, num2 都是正的但加總是負的或 num1, num2 都是負的但加總是正的,那就可以成功回傳 -1,單來說就是輸入兩個整數導致 overflow 就好 按照上述邏輯這樣輸入就成功了 ![TwoSumSolution](https://hackmd.io/_uploads/HJo7zDD96.png =80%x)