반응형

IDA Pro를 설치하고 파일을 disassembling 해 보면 밝은 스킨이 적용된 화면이 나타난다.

 

 

어두운 스킨 적용을 위해 아래 링크에서 파일을 다운 받는다. (

IDASkins-master.zip
다운로드

이 파일을 받아도 된다)

https://github.com/zyantific/IDASkins

 

다운 받아서 압축을 풀고 plugins 폴더를 확인해 보면 아래와 같은 폴더와 파일이 있다.

 

IDA Pro가 설치된 폴더 - plugins 폴더에 모두 복사한다. (idaskins.py는 그림에 표시되지 않았다)

 

IDA Pro를 실행시키고 Edit - Plugins - IDASkins: Settings를 선택한다. (Ctrl + Shift + S)

 

 

Theme selection 에서 IDASkins dark를 선택한다.

 

Options - Colors... 를 선택 한다.

 

Import 를 선택하고 plugins\idaskins\themes\idaskins-dark\ida-consonance.clr 을 선택한다.

 

원하는 파일을 disassembling 해 보면 아래와 같은 skin이 적용되어 표시 된다.

 

 

반응형

'Reverse Engineering' 카테고리의 다른 글

x64dbg Color Scheme 바꾸기  (0) 2019.02.19
Cheat Engine으로 Pointer 찾기  (2) 2019.02.13
Back to user mode  (4) 2019.02.10
Windows 10에서 *.hlp 파일 열기  (10) 2019.02.05
ollydbg Jump 위치 표시  (2) 2019.02.02
Posted by J-sean
:
반응형

ollydbg에서 jump 명령어 실행 시 이동되는 위치는 시각적으로 명확히 표시되지 않는것이 기본 세팅 이다.



ollydbg.ini 파일에서 아래와 같은 항목들의 값을 1로 바꿔 준다.

  • Show jump path
  • Show jumpfrom path
  • Show path if jump is not taken



ollydbg를 실행해서 확인하면 아래와 같이 화살표로 jump 가 명확히 표시된다.


반응형

'Reverse Engineering' 카테고리의 다른 글

x64dbg Color Scheme 바꾸기  (0) 2019.02.19
Cheat Engine으로 Pointer 찾기  (2) 2019.02.13
Back to user mode  (4) 2019.02.10
Windows 10에서 *.hlp 파일 열기  (10) 2019.02.05
IDA Pro Skin 바꾸기  (1) 2019.02.04
Posted by J-sean
:
반응형

SQLite는 별도의 서버 없이 디스크 기반으로 SQL 쿼리를 지원하는 가벼운 C 라이브러리 데이터베이스 이다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
import sqlite3
 
dbpath = "fruit.db"
conn = sqlite3.connect(dbpath)
# Opens a connection to the SQLite database file database.
# By default returns a Connection object, unless a custom factory
# is given. You can use ":memory:" to open a database connection to 
# a database that resides in RAM instead of on disk.
cur = conn.cursor()
# The cursor method accepts a single optional parameter factory.
# If supplied, this must be a callable returning an instance of
# Cursor or its subclasses.
 
cur.executescript("""
drop table if exists items;
create table items(
    item_id integer primary key,
    name text unique,
    price integer
);
insert into items(name, price) values("Apple", 800);
insert into items(name, price) values("Orange", 700);
insert into items(name, price) values("Banana", 430);
""")
# This is a nonstandard convenience method for executing
# multiple SQL statements at once. It issues a COMMIT statement
# first, then executes the SQL script it gets as a parameter.
 
conn.commit()
# This method commits the current transaction. If you don’t call
# this method, anything you did since the last call to commit()
# is not visible from other database connections. If you wonder
# why you don’t see the data you’ve written to the database, please
# check you didn’t forget to call this method.
 
cur.execute("select * from items")
# This is a nonstandard shortcut that creates a cursor object by
# calling the cursor() method, calls the cursor’s execute() method
# with the parameters given, and returns the cursor.
item_list = cur.fetchall()
# Fetches all (remaining) rows of a query result, returning a list.
# Note that the cursor’s arraysize attribute can affect the performance
# of this operation. An empty list is returned when no rows are available.
for it in item_list:
    print(it)
 
print()
 
cur.execute("insert into items(name, price) values('Grape', 500)")
conn.commit()
 
cur.execute("select item_id, name, price from items")
item_list = cur.fetchall()
for it in item_list:
    print(it)
 
print()
 
cur.execute("insert into items(name, price) values(?, ?)", ("Strawberry"800))
#conn.commit() 67라인에서 commit()을 호출 하므로 굳이 여기서 할 필요는 없다.
 
data = [("Mango"250), ("Kiwi"740), ("Peach"650)]
cur.executemany("insert into items(name, price) values(?, ?)", data)
# Executes an SQL command against all parameter sequences or mappings found in the
# sequence seq_of_parameters.
conn.commit()
 
cur.execute("select item_id, name, price from items")
item_list = cur.fetchall()
for it in item_list:
    print(it)
 
print()
 
price_range = (600700)
cur.execute("select * from items where name = 'Kiwi' or (price >= ? and price <= ?)",
            price_range)
item_list = cur.fetchall()
for it in item_list:
    print("Name: ", it[1], ", Price: ", it[2])
 
for it in item_list:
    print("ID: %s, Name: %s, Price: %s" %it) # it 자체(튜플)를 전달해도 된다.
 
print("\nStrawberry를 Watermelon으로 변경, Orange 삭제")
 
cur.execute("update items set name = 'Watermelon', price = 1500 where name = 'Strawberry'")
cur.execute("delete from items where name = 'Orange'")
cur.execute("select * from items")
conn.commit()
 
item_list = cur.fetchall()
for it in item_list:
    print(it)
 
cur.close()
conn.close()
cs




fruit.db 파일이 생성 된다.



반응형
Posted by J-sean
:

CSV 분석

Machine Learning 2019. 1. 20. 12:48 |
반응형

Python 기본 라이브러리 csv를 이용해 CSV(comma-separated values) 형식을 분석 할 수 있다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import locale
import csv
 
lo = locale.getdefaultlocale()
# Tries to determine the default locale settings and returns them as a tuple of
# the form (language code, encoding).
print("Default language code: " + lo[0], "Default encoding: " + lo[1], sep = "\n", end = "\n\n")
 
filename = "list.csv"
with open(filename, "rt", encoding="euc_kr") as f:
    csv_data = f.read()
 
data = []
rows = csv_data.split("\n")
for row in rows:
    if row == "":
        continue
    cells = row.split(",")
    data.append(cells)
 
for c in data:
    print("%-8s %8s" %(c[1], c[2]))
 
print()
 
#Python csv library
with open(filename, "at", encoding="euc_kr") as f:
    # 'a' - open for writing, appending to the end of the file if it exists
    # For binary read-write access, the mode 'w+b' opens and truncates the file to 0 bytes.
    # 'r+b' opens the file without truncation.
    csv_writer = csv.writer(f, delimiter = ",", quotechar = '"')
    csv_writer.writerow(["101""Math""4300"])
    csv_writer.writerow(["102""Physics""4800"])    
    csv_writer.writerow(["103""English""5700"])
# stream position을 바꾸고 싶으면 io module의 seek()을 f.seek(...)처럼 사용 한다.
# seek(offset[, whence])
# Change the stream position to the given byte offset. offset is interpreted relative to the
# position indicated by whence. The default value for whence is SEEK_SET. Values for whence are:
# SEEK_SET or 0 – start of the stream (the default); offset should be zero or positive
# SEEK_CUR or 1 – current stream position; offset may be negative
# SEEK_END or 2 – end of the stream; offset is usually negative
# Return the new absolute position.
 
with open(filename, "rt", encoding="euc_kr") as f:
    csv_reader = csv.reader(f, delimiter = ",", quotechar = '"')
    for cells in csv_reader:
        if cells == []:
            continue
        print("%-8s %8s" %(cells[1], cells[2]))
cs




list.csv:


결과:


실행 후 list.csv:



반응형
Posted by J-sean
:

JSON 분석

Machine Learning 2019. 1. 18. 20:14 |
반응형

Python 기본 라이브러리 json을 이용해 JSON (JavaScript Object Notation) 형식을 분석할 수 있다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import urllib.request as req
import os.path
import json
 
url = "https://api.github.com/repositories"
filename = "repositories.json"
 
if not os.path.exists(filename):
    #req.urlretrieve(url, filename)
    # Legacy interface. It might become deprecated at some point in the future.
    with req.urlopen(url) as contents:
        jsn = contents.read().decode("utf-8"# .decode("utf-8")이 없으면 jsn에는 str이 아닌 bytes가 저장 된다.
        # If the end of the file has been reached, read() will return an empty string ('').
        print(jsn)        
        # print(json.dumps(jsn, indent="\t")) 는 indent가 적용되어 출력되어야 하지만 원본이 indent가 적용되어 있지
        # 않아 indent 없이 출력 된다.
        with open(filename, mode="wt", encoding="utf-8") as f:
            f.write(jsn)
 
with open(filename, mode="rt", encoding="utf-8") as f:
    items = json.load(f) # JSON 문서를 갖고 있는 파일 포인터 전달. loads()는 JSON 형식의 문자열 전달
    for item in items:
        print("Name:", item["name"], "Login:", item["owner"]["login"])
 
test = {
    "Date" : "2019-01-17",
    "Time" : "21:30:24",
    "Location" : {
        "Town" : "Franklin",
        "City" : "Newyork",
        "Country" : "USA"
        }
    }
 
= json.dumps(test, indent="\t")
# Serialize obj to a JSON formatted str
# If indent is a non-negative integer or string, then JSON array elements and object members will be pretty-printed
# with that indent level. An indent level of 0, negative, or "" will only insert newlines. None (the default) selects
# the most compact representation. Using a positive integer indent indents that many spaces per level. If indent is a
# string (such as "\t"), that string is used to indent each level.
print(s)
 
with open("dump.json", mode="wt") as f:
    json.dump(test, f, indent="\t")
# Serialize obj as a JSON formatted stream to fp (a .write()-supporting file-like object)
cs


출력 결과 처음 부분.


출력 결과 마지막 부분.


write()으로 만든 repositories.json과 dump()으로 만든 dump.json 파일.



반응형
Posted by J-sean
:
반응형

2021.09.25 - [C, C++] - Qt6 설치 및 간단한 사용법

2021/02/13 - [C, C++] - Linux(Ubuntu) Qt5 Image Display - 리눅스(우분투) Qt5 이미지 디스플레이

2021/02/12 - [C, C++] - Linux(Ubuntu) Qt5 GUI Programming - 리눅스(우분투) Qt5 GUI 프로그래밍

 

Qt는 GUI 프로그램 개발에 널리 쓰이는 크로스 플랫폼 프레임워크이다. 홈페이지에서 Open Source 버전을 다운 받아 실행 한다.

 

기본설정에서 MSVC 2017 64-bit만 추가한다.

 

Qt 설치가 완료되면 Visual Studio에서도 사용 할 수 있도록 Extension을 설치 한다.

 

Online에서 qt를 검색해 Qt Visual Studio Tools를 설치한다.

 

설치가 완료되면 Qt Options를 선택 한다.

 

 

Qt가 설치된 위치의 msvc2017_64 폴더를 Add 한다.

 

설치가 완료 되었으면 Qt Creator를 실행하고 Qt Widgets Application 프로젝트를 만들어 준다.

 

프로젝트 폴더 선택 외에는 기본값으로 진행 한다.

 

설정이 완료되면 아래와 같은 화면이 나온다.

 

 

Forms - Mainwindow.ui 디자인 화면에서 PushButton과 Label을 적당한 위치에 배치한다. Label은 기본 크기보다 약간 크게 늘려 준다.

Label의 Property에서 alignment - Horizontal을 AlignHCenter로 바꿔준다.

 

PushButton에서 오른쪽 클릭 - Go to slot... 을 선택한다.

 

QAbstractButton - clicked() 를 선택한다.

 

mainWindow.cpp 에 on_pushButton_clicked() 가 생성된다.

 

 

mainwindow.h 에 QMessageBox 헤더 파일을 include 하고 IsClicked, OriginalStatus, MsgBox 멤버 변수를 추가한다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
 
#include <QMainWindow>
#include <QMessageBox>
 
namespace Ui {
class MainWindow;
}
 
class MainWindow : public QMainWindow
{
    Q_OBJECT
 
public:
    explicit MainWindow(QWidget *parent = nullptr);
    ~MainWindow();
 
private slots:
    void on_pushButton_clicked();
 
private:
    Ui::MainWindow *ui;
 
    bool IsClicked;
    QString OriginalStatus;
    QMessageBox MsgBox;
};
 
#endif // MAINWINDOW_H
cs

 

mainwindow.cpp 에서 constructor와 on_pushButton_clicked() 를 아래와 같이 수정해 준다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include "mainwindow.h"
#include "ui_mainwindow.h"
 
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
 
    IsClicked = false;
    OriginalStatus = ui->pushButton->styleSheet();
    ui->label->setText("Unchanged");
    MsgBox.setWindowTitle("Sean");
    MsgBox.setText("Button Color Change");
    MsgBox.setInformativeText("Do you want to change button color?");
    MsgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel);
    MsgBox.setDefaultButton(QMessageBox::Yes);
}
 
MainWindow::~MainWindow()
{
    delete ui;
}
 
void MainWindow::on_pushButton_clicked()
{
    if (IsClicked == false)
    {
        int ret = MsgBox.exec();
 
        switch(ret)
        {
            case QMessageBox::Yes:
                ui->pushButton->setStyleSheet("color: blue;"
                                              "background-color: red;");
                ui->label->setText("Changed");
                IsClicked = !IsClicked;
                break;
 
            case QMessageBox::No:
                ui->label->setText("No");
                break;
 
            default:
                ui->label->setText("Cancel");
                break;
        }
    } else {
        IsClicked = !IsClicked;
        ui->pushButton->setStyleSheet(OriginalStatus);
        ui->label->setText("Unchanged");
    }
}
cs

 

 

빌드(Ctrl + B) 후 실행 (Ctrl + R) 한다.

 

PushButton을 클릭하면 MessageBox가 나온다.

 

Yes를 클릭하면 PushButton의 색과 Label 의 text가 변한다.

 

 

반응형
Posted by J-sean
:
반응형

Beautifulsoup을 이용해 XML을 분석할 수 있다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
from bs4 import BeautifulSoup
import urllib.request as req
import os.path
 
url = "http://www.weather.go.kr/weather/forecast/mid-term-rss3.jsp?stnId=108"
# 기상청 날씨누리 전국 중기예보 RSS
filename = "forecast.xml"
 
if not os.path.exists(filename):
    #req.urlretrieve(url, savename)
    # Legacy interface. It might become deprecated at some point in the future.
    with req.urlopen(url) as contents:
        xml = contents.read().decode("utf-8")
        # If the end of the file has been reached, read() will return an empty string ('').
        #print(xml)
        with open(filename, mode="wt") as f:
            f.write(xml)
 
with open(filename, mode="rt") as f:
    xml = f.read()
    soup = BeautifulSoup(xml, "html.parser")
    # html.parser는 모든 태그를 소문자로 바꾼다.
    #print(soup)
 
    print("[", soup.find("title").string, "]")
    print(soup.find("wf").string, "\n")
 
    # 날씨에 따른 지역 분류
    info = {}    # empty dicionary
    for location in soup.find_all("location"):
        name = location.find("city").string
        weather = location.find("wf").string
        if not (weather in info):
            info[weather] = []    # empty list. dictionary는 list를 value로 가질 수 있다.
        info[weather].append(name)
 
    for weather in info.keys():    # Return a new view of the dictionary’s keys.
        print("■", weather)
        for name in info[weather]:
            print("|-", name)
cs




반응형
Posted by J-sean
:
반응형

JSON (JavaScript Object Notation)은 가벼운 data 교환 포멧이다. C++이 공식으로 지원하는 형식은 아니지만 분석에 사용 가능한 여러가지 라이브러리가 있다. 그 중 JsonCpp의 사용 방법이다.


홈페이지에서 소스를 다운 받고 압축을 풀면 아래와 같은 파일들이 나온다.


amalgamate.py를 실행한다.


dist라는 폴더에 소스파일과 헤더 파일이 생성된다.


makefiles - mscv2010 - jsoncpp.sln을 실행 한다.


Retarget Projects가 실행된다.


3개의 프로젝트가 나타난다.


각 프로젝트의 Property Pages - Configuration Properties - C/C++ - Code Generation - Runtime Library를 /MDd로 바꿔 준다.


Build 해 준다.


makefiles - msvc2010 - Debug 폴더에 lib_json.lib가 생성된다.


JsonCpp를 사용할 프로젝트를 만들고 Include Directory(jsoncpp-master\include)와 Library Directory(jsoncpp-master\makefiles\msvc2010\Debug)를 추가해 준다.




쓰기 예제

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#pragma comment (lib, "lib_json.lib")
 
#include <iostream>
#include <fstream>
#include "json/json.h"
 
using namespace std;
using namespace Json;
 
int main()
{
    ofstream json_file;
    json_file.open("JSON_DATA.json");
 
    Value Computer;
    Computer["CPU"= "I7";
    Computer["RAM"= "16G";
 
    Value Language;
    Language["C++"= "Visual Studio";
    Language["Python"= "IDLE";
    
    Computer["Program"= Language;
    Computer["HDD"= "2TB";
 
    Value Cable;
    Cable.append("Power");
    Cable.append("Printer");
    Cable.append("Mouse");
 
    Computer["Computer"]["Cable"= Cable;
 
    Value number;
    number["Int"= 123;
    number["Double"= 456.012;
    number["Bool"= true;
 
    Computer["Computer"]["Number"= number;
 
    StreamWriterBuilder builder;
    builder["commentStyle"= "None";
    builder["indentation"= "    ";  // Tab
    unique_ptr<Json::StreamWriter> writer(builder.newStreamWriter());
 
    // 알파벳 순으로 write 된다.
    writer->write(Computer, &cout);
    writer->write(Computer, &json_file);
    cout << endl;  // add lf and flush
 
    json_file.close();
 
    return 0;
}
cs


아래와 같은 결과가 출력 된다.


같은 결과의 JSON_DATA.json 파일이 생성 된다.

읽기 예제

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#pragma comment (lib, "lib_json.lib")
 
#include <iostream>
#include <fstream>
#include "json/json.h"
 
using namespace std;
using namespace Json;
 
int main()
{
    ifstream json_dir("JSON_DATA.json");
    CharReaderBuilder builder;
    builder["collectComments"= false;
    Value value;
 
    JSONCPP_STRING errs;
    bool ok = parseFromStream(builder, json_dir, &value, &errs);
 
    if (ok == true)
    {
        cout << "CPU: " << value["CPU"<< endl;
        cout << "Program Python: " << value["Program"]["Python"<< endl;
        cout << "Computer Cable: " << value["Computer"]["Cable"<< endl;
        cout << "Computer Cable[0]: " << value["Computer"]["Cable"][0<< endl;
        cout << endl;
 
        cout << "Computer Number Int(as int): " << value["Computer"]["Number"].get("Int"-1).asInt() << endl;
        // "Int" 값이 없으면 -1 반환.
        cout << "Computer Number Int(as int): " << value["Computer"]["Number"]["Int"].asInt() << endl;
        // "Int" 값이 없으면 0 반환.
        cout << "Computer Number Double(as double): " << value["Computer"]["Number"].get("Double"-1).asDouble() << endl;
        // "Double" 값이 없으면 -1 반환.
        cout << "Computer Number Double(as string): " << value["Computer"]["Number"].get("Double""Empty").asString() << endl;
        // "Double" 값이 없으면 Empty 반환.
        cout << "Computer Number Bool(as bool): " << value["Computer"]["Number"].get("Bool"false).asBool() << endl;
        // "Bool" 값이 없으면 false 반환.
        cout << endl;
 
        cout << "Root size: " << value.size() << endl;
        cout << "Program size: " << value["Program"].size() << endl;
        cout << "Computer Cable size: " << value["Computer"]["Cable"].size() << endl;
        cout << endl;
 
        int size = value["Computer"]["Cable"].size();
        // size() 값을 for 문에서 그대로 비교하면 warning C4018가 발생 한다.
        for (int i = 0; i < size; i++)
            cout << "Computer Cable: " << value["Computer"]["Cable"][i] << endl;
        cout << endl;
 
        for (auto i : value["Computer"]["Cable"])
            cout << "Computer Cable: " << i << endl;
    }
    else
    {
        cout << "Parse failed." << endl;
    }
 
    return 0;
}
cs


아래와 같은 결과가 출력 된다.



반응형

'C, C++' 카테고리의 다른 글

Qt 스프라이트 애니매이션  (0) 2019.02.21
Qt 설치 및 간단한 사용 예  (4) 2019.01.16
Console 어플리케이션에 이미지 디스플레이 하기  (0) 2018.11.22
Python C API  (0) 2018.11.21
MySQL C API  (0) 2018.11.20
Posted by J-sean
: