2019年4月30日星期二

指针函数与函数指针的区别

指针函数与函数指针的区别


一、
在学习arm过程中发现这指针函数函数指针容易搞错,所以今天,我自己想一次把它搞清楚,找了一些资料,首先它们之间的定义:
1、指针函数是指带指针的函数,即本质是一个函数。函数返回类型是某一类型的指针
     类型标识符    *函数名(参数表)
      int *f(xy);

首先它是一个函数,只不过这个函数的返回值是一个地址值。函数返回值必须用同类型的指针变量来接受,也就是说,指针函数一定有函数返回值,而且,在主调函数中,函数返回值必须赋给同类型的指针变量。
表示:
float *fun();
float *p;
p = fun(a);
注意指针函数与函数指针表示方法的不同,千万不要混淆。最简单的辨别方式就是看函数名前面的指针*号有没有被括号()包含,如果被包含就是函数指针,反之则是指针函数。
来讲详细一些吧!请看下面
 指针函数:
    
当一个函数声明其返回值为一个指针时,实际上就是返回一个地址给调用函数,以用于需要指针或地址的表达式中。
    
格式:
         
类型说明符 * 函数名(参数)
    
当然了,由于返回的是一个地址,所以类型说明符一般都是int

    
例如:int *GetDate();
          int * aaa(int,int);
    
函数返回的是一个地址值,经常使用在返回数组的某一元素地址上。


        int * GetDate(int wk,int dy);

        main()
        {
            int wk,dy;
            do
            {
                printf(Enter week(1-5)day(1-7)\n);
                scanf(%d%d,&wk,&dy);
            }
            while(wk<1||wk>5||dy<1||dy>7);
            printf(%d\n,*GetDate(wk,dy));
        }

        int * GetDate(int wk,int dy)
        {
            static int calendar[5][7]=
            {
               {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,-1}
            };
            return &calendar[wk-1][dy-1];
        }
        
程序应该是很好理解的,子函数返回的是数组某元素的地址。输出的是这个地址里的值。



2、函数指针是指向函数的指针变量,即本质是一个指针变量。
 int (*f) (int x); /* 声明一个函数指针 */
 f=func; /* func函数的首地址赋给指针f */

指向函数的指针包含了函数的地址,可以通过它来调用函数。声明格式如下:
        
类型说明符 (*函数名)(参数)
    
其实这里不能称为函数名,应该叫做指针的变量名。这个特殊的指针指向一个返回整型值的函数。指针的声明笔削和它指向函数的声明保持一致。

        
指针名和指针运算符外面的括号改变了默认的运算符优先级。如果没有圆括号,就变成了一个返回整型指针的函数的原型声明。
    
例如:
        void (*fptr)();
    
把函数的地址赋值给函数指针,可以采用下面两种形式:
        fptr=&Function;
        fptr=Function;
    
取地址运算符&不是必需的,因为单单一个函数标识符就标号表示了它的地址,如果是函数调用,还必须包含一个圆括号括起来的参数表。
    
可以采用如下两种方式来通过指针调用函数:
        x=(*fptr)();
        x=fptr();
    
第二种格式看上去和函数调用无异。但是有些程序员倾向于使用第一种格式,因为它明确指出是通过指针而非函数名来调用函数的。下面举一个例子:

        void (*funcp)();
        void FileFunc(),EditFunc();

        main()
        {
            funcp=FileFunc;
            (*funcp)();
            funcp=EditFunc;
            (*funcp)();
        }

        void FileFunc()
        {
            printf(FileFunc\n);
        }

        void EditFunc()
        {
            printf(EditFunc\n);
        }

        
程序输出为:
            FileFunc
            EditFunc

主要的区别是一个是指针变量,一个是函数。在使用是必要要搞清楚才能正确使用

二、指针的指针
    
指针的指针看上去有些令人费解。它们的声明有两个星号。例如:
        char ** cp;
    
如果有三个星号,那就是指针的指针的指针,四个星号就是指针的指针的指针的指针,依次类推。当你熟悉了简单的例子以后,就可以应付复杂的情况了。当然,实际程序中,一般也只用到  二级指针,三个星号不常见,更别说四个星号了。
    
指针的指针需要用到指针的地址。
        char c='A';
        char *p=&c;
        char **cp=&p;
    
通过指针的指针,不仅可以访问它指向的指针,还可以访问它指向的指针所指向的数据。下面就是几个这样的例子:
        char *p1=*cp;
        char c1=**cp;
    
你可能想知道这样的结构有什么用。利用指针的指针可以允许被调用函数修改局部指针变量和处理指针数组。

        void FindCredit(int **);

        main()
        {
            int vals[]={7,6,5,-4,3,2,1,0};
            int *fp=vals;
            FindCredit(&fp);
            printf(%d\n,*fp);
        }

        void FindCredit(int ** fpp)
        {
            while(**fpp!=0)
            if(**fpp<0) break;
            else (*fpp)++;
        }

    
首先用一个数组的地址初始化指针fp,然后把该指针的地址作为实参传递给函数FindCredit()FindCredit()函数通过表达式**fpp间接地得到数组中的数据。为遍历数组以找到一个负值,FindCredit()函数进行自增运算的对象是调用者的指向数组的指针,而不是它自己的指向调用者指针的指针。语句(*fpp)++就是对形参指针指向的指针进行自增运算的。但是因为*运算符高于++运算符,所以圆括号在这里是必须的,如果没有圆括号,那么++运算符将作用于二重指针fpp上。
三、指向指针数组的指针
    
指针的指针另一用法旧处理指针数组。有些程序员喜欢用指针数组来代替多维数组,一个常见的用法就是处理字符串。

        char *Names[]=
        {
             Bill,
             Sam,
             Jim,
             Paul,
             Charles,
             0
        };

        main()
        {
            char **nm=Names;
            while(*nm!=0) printf(%s\n,*nm++);
        }

    
先用字符型指针数组Names的地址来初始化指针nm。每次printf()的调用都首先传递指针nm指向的字符型指针,然后对nm进行自增运算使其指向数组的下一个元素(还是指针)。注意完成上述认为的语法为*nm++,它首先取得指针指向的内容,然后使指针自增。
    
注意数组中的最后一个元素被初始化为0while循环以次来判断是否到了数组末尾。具有零值的指针常常被用做循环数组的终止符。程序员称零值指针为空指针(NULL)。采用空指针作为终止符,在树种增删元素时,就不必改动遍历数组的代码,因为此时数组仍然以空指针作为结束。


2019年4月28日星期日

python 发送16进制

#-*- encoding: utf-8 -*-

import json
import socket
import sys
import binascii

reload(sys)
sys.setdefaultencoding('utf-8')

if __name__=="__main__":
        s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
        s.connect(("your_host_name", your_port))
        s.send("\xab\xcd\x34\x12\x1f\x00_some_orther_data")  # 前面为十六进制数据,后面可接字符串等正文
        print s.recv(1024)
        s.close()

2019年4月27日星期六

python表达式

Python的表达式写法与C/C++类似。只是在某些写法有所差别。

主要的算术运算符与C/C++类似。+, -, *, /, //, **, ~, %分别表示加法或者取正、减法或者取负、乘法、除法、整除、乘方、取补、取模。>>, <<表示右移和左移。&, |, ^表示二进制的AND, OR, XOR运算。>, <, ==, !=, <=, >=用于比较两个表达式的值,分别表示大于、小于、等于、不等于、小于等于、大于等于。在这些运算符里面,~, |, ^, &, <<, >>必须应用于整数。
Python使用and, or, not表示逻辑运算。
---------------------
作者:AISYE
来源:CSDN
原文:https://blog.csdn.net/ai_s_ye/article/details/45150477
版权声明:本文为博主原创文章,转载请附上博文链接!

2019年4月26日星期五

ble pairing

Bluetooth Low Energy (BLE) is becoming one of the most common wireless standards used today in IoT devices. Likewise, it is also becoming more commonly used in applications where sensitive information is being transferred. As a consequence, IoT devices makers looking to integrate BLE into their products should be aware of the security features and limitations of this technology. In this post, I will try to provide a basic overview of BLE security features. If you are not already familiar with BLE, I suggest you to watch this nice webinar by Nordic Semiconductor before.

Overview

A BLE connection is said to operate at a specific security mode for which there are several security levels. The required security mode/level of a connection may change from time to time, leading to procedures to increase that level. Note that each connection starts its lifetime in Security Mode 1, Level 1.
When two devices, which initially do not have security, wish to do something that requires security, the devices must first pair. This process is triggered by a Central device (e.g. a smartphone) that is attempting to access a data value (a “characteristic”) on a Peripheral device that requires authenticated access. Pairing involves authenticating the identity of two devices, encrypting the link using a short-term key (STK) and then distributing long-term keys (LTK) used for encryption. The LTK is saved for faster reconnection in the future, that is termed Bonding.
This process is shown the following figure:
Bluetooth paring process
The new security level of the connection is based on the method of pairing performed and its selection is based on the I/O capabilities of each device. The security level of any subsequent reconnections is based on the level achieved during the initial pairing.
The role each device plays is defined in the Security Manager (SM) portion of the BLE stack. They are the Initiator (the central), and the Responder (the peripheral).

Encryption and Authentication

The encryption in Bluetooth LE is based on 128-bit Advanced Encryption Standard — Counter with CBC-MAC (AES-CCM). LTK is used with this algorithm to create the 128-bit “shared secret” key.
Authentication is provided in Bluetooth (LE) by digitally signing the data using the connection Signature Resolving Key (CSRK). The sending device places a signature after the Data PDU. The receiver verifies the signature using the CSRK.

Security Modes and Levels of a Connection

For a BLE connection,the Generic Access Protocol (GAP) defines two security modes, along with several security levels per mode.

Security Mode 1

Security Mode 1 enforces security by means of encryption and contains four levels:
  • Security Level 1: No Security (No authentication and no encryption)
  • Security Level 2: Unauthenticated pairing with encryption
  • Security Level 3: Authenticated pairing with AES-CCM encryption
  • Security Level 4: Authenticated LE Secure Connections pairing with encryption. Level 4 uses Elliptic Curve Diffie-Hellman P-256 (ECDH) and AES-CCM encryption.

Security Mode 2

Security Mode 2 enforces security by means of data signing and contains two levels:
  • Security Level 1: Unauthenticated pairing with data signing
  • Security Level 2: Authenticated pairing with data signing

Mixed Security Mode

Mixed Security Mode is when a device is required to support both Security Mode 1 and 2, i.e., it needs to support signed and unsigned data. Secure Connection Only Mode is Secure Mode 1 with Security Level 4, meaning that all incoming and outgoing traffic in a Bluetooth device involve authenticated connections and encryption only.
Each connection starts its lifetime in Security Mode 1, level 1 and can later be upgraded to any security level by means of an authentication procedure discussed below. When pairing, the method/algorithm chosen determines if the pairing performed a strong authentication or not. Unauthenticated pairings occur in situations where the device could not authenticate itself (for example, if it has no input/output capabilities).
Further details are provided in Vol. 3, Part C, Section 10 of the BLE v4.2 Core Specification.

Pairing Modes

Pairing involves authenticating the identity of the 2 devices to be paired, usually through a process of sharing a secret. Once authenticated, the link is encrypted and keys are distributed to allow security to be restarted on a reconnection much more quickly. If these keys are saved for a future time, the devices are said to be Bonded. The pairing happens in 3 phases.

Phase 1

In phase one, the two devices let each other know what they are capable of doing. The values they are reading are Attribution Protocol (ATT) values and live at layer 4 with L2CAP. They are not encrypted. These values determine which pairing method is going to be used in phase two and what the devices can do and what they expect. For instance, the peer’s input and output capabilities which are selected from one of the following possibilities determine the connection security level. These capabilities are communicated between the devices by using the Security Manager (SM) Pairing Request message. They are: No Input No Output, Display Only, Display Yes/No, Keyboard Only and Keyboard Display.

Phase 2

In phase 2, the purpose is to generate a Short Term Key (STK). This is possible with the devices agreeing on a Temporary Key (TK) mixed with some random numbers which gives them the STK. The STK itself is never transmitted between devices. The use of STK is commonly known as LE legacy pairing. However, if the Secure Connection Only Mode is being used, a Long Term Key (LTK) is generated at this phase (instead of an STK) and this is known as LE Secure Connections.

Phase 3

In phase 3, the key from phase two is used to distribute the rest of the keys needed for communications. Whereas an LTK wasn’t generated in phase two, one is generated in phase three. In this phase, data like the Connection Signature Resolving Key (CSRK) for data signing or the Identity Resolving Key (IRK) for private MAC address generation and lookup are generated.
The pairing flowchart which applies to both legacy pairing and secure connections.

Pairing Procedures

A pairing procedure involves an exchange of Security Manager Protocol packets to generate a temporary encryption key called the Short Term Key (STK) as depicted in the diagram above. During the packet exchange, the two peers negotiate one of the following STK generation methods:
Just Works: The STK is generated on both sides, based on the packets exchanged in plain text. This method provides no security against man-in-the-middle (MITM) attacks.
Passkey Display: One of the peers displays a randomly generated 6-digit passkey and the other side has asked to enter it. In some cases, both sides enter the key if no display is available. This method provides protection against MITM attacks.
Out of Band (OOB): In this method, the additional data can be transferred by other means than the BLE radio (such as another wireless technology like NFC). This method also provides protection against MITM attacks.
Numeric Comparison (LE Secure Connections Pairing) and only with BLE 4.2: This method uses an algorithm called Elliptic curve Diffie–Hellman (ECDH) for key generation and a new pairing procedure for the key exchange. The link is encrypted using LTK from Phase 2
The table below is a reference to determine/for determining the pairing method based on the two devices I/O capabilities and the role each device plays in the process.
Pairing procedure and I/O capabilities

Bonding Modes and Procedure

There are two modes:
  • Non-Bondable Mode: this is the default bondable mode for devices. This means the device will not accept bonding. No keys will be exchanged or stored by the device.
  • Bondable Mode: to accept a bonding request, the Peripheral must set the bonding bit in the authentication requirements of the Pairing Request message during pairing. The device exchanges security keys and stores them.
If a Central wants to bond with a Peripheral device it believes is bondable, it uses the bondable procedure. It initiates pairing with the same bonding bit set in the authentication requirements of the Pairing Request message. If the Peripheral device is bondable, it will respond with the bonding bit set. If all this happens, the keys will be distributed after the link is encrypted and then the keys are stored. Once the keys have been distributed and stored, the pair of devices are said to be Bonded.

Conclusion

BLE offers several features for securing communication between devices, each with its own advantages and limitations.
As IoT devices makers, we take care of implementing BLE features into their designs. We are aware of the specific security threats facing BLE and make our best effort to leverage BLE’s security features to mitigate them.

Annexe 1: Summary of 4.0 and 4.2 differences

Bluetooth 4.2 introduced a new security model, LE Secure connections. LE Secure Connections use an algorithm called Elliptic curve Diffie–Hellman (ECDH) for key generation and a new pairing procedure for the key exchange.
Using LE Secure Connections with the ECDH algorithms to generate public/private key pairs, the Security Manager protects the communication from passive eavesdropping regardless of the I/O capabilities and pairing methods (Numeric Comparison, Just Works, Passkey Entry, and Out Of Band). It will provide protection from Man-In-The-Middle (MITM) attacks if the application uses Numeric Comparison, Passkey Entry, and Out Of Band as the pairing method.

References

Bluetooth Core Specification, ver. 4.1, Bluetooth SIG, December 2013
Bluetooth Core Specification, ver. 4.2, Bluetooth SIG, December 2014
Rosa, T. (2013, May 23). Bypassing Passkey Authentication in Bluetooth Low Energy. Retrieved August 01, 2016, from https://eprint.iacr.org/2013/309.pdf
Ryan, M. (2013). Bluetooth: With Low Energy Comes Low Security. Retrieved August 01, 2016, from https://www.usenix.org/conference/woot13/workshop-program/presentation/ryan
This post has been posted on Rtone blog. I would like to thanks Jenny Baur for the review.

2019年4月11日星期四

BLE

Bluetooth Low Energy
Now that we have read about ZigBee, the other most common
communication protocol is BLE. BLE has applications in a number of areas
in IoT, especially because it is one of the communication protocols with
which smartphones can speak.
You will find BLE in a number of smart devices including those
used for health care, smart home automation, retail, smart enterprises,
and
so on. BLE has a number of advantages over other communication
protocols, including the ability to conserve power for a longer duration of
time, extremely low usage of resources even with higher amounts of data
transfer, and so on.
Bluetooth was originally designed by Nokia with the name Wibree
in 2006, which was then later adopted by the Bluetooth Special Interest
Group (SIG) in 2010. Later on, the Bluetooth 4.0 core specification was
released with the focus on designing a radio standard with low power
consumption targeting use in devices with low resources, power, and
bandwidth.
BLE Internals and Association
Before jumping into BLE security and the various exploitation techniques,
let’s have a look at some of the BLE internals, so that we have a greater in-
depth understanding of the foundational concepts when we are working
with BLE-based IoT devices. Figure 10-19 shows the BLE stack structure.








As you can see from Figure 10-19, the BLE stack consists of two
different layers—Host and Controller—bound via the Host Controller
Interface (HCI). All the different components in various layers perform
their own functionality; for example, the Physical layer is responsible for
all the modulation and demodulation of the signals; the Link layer handles
CRC generation, encryption, and defining how devices communicate with
each other; and the Logical Link Control and Adaption Protocol (L2CAP)
takes multiple data formats from the upper layers and puts them into a
BLE packet structure.
Figure 10-19. Bluetooth Low Energy stack (Source: https://www.
bluetooth.com/specifications/bluetooth-core-specification)
Chapter 10 exploiting ZigBee and Ble
284
At the very top of the BLE stack, inside the Host layer, you will notice a
couple of more interesting components such as Attribute Protocol (ATT),
Generic Attribute Profile (GATT), and Generic Access Profile (GAP).
Let’s explore what the functionalities of GAP and GATT are, as these
are the two most important components in the BLE stack, and also
something that you will encounter very frequently during your security
research.
• GAP is responsible for all the discovery and related
aspects in any BLE network. ATT defines the client/
server protocol for data exchange, which is then
grouped together into meaningful services using the
GATT.
• GATT is responsible for the entire exchange of all user
data and profile information in a BLE connection.
So as you can imagine, it will be GATT (or ATT) that we are mostly
concerned with during our further security research journey. As we go
deep inside a BLE connection, it is also vital to understand how all of the
data are stored on a device in a BLE connection. This is better illustrated in
Figure 10-20.






part1- network pene

exploitation techniques on it. Also, the IP and MAC addresses will be
useful for us if we want to take control of the smart plug, as the commands
that the mobile application sends to the device will require both these
values.
Go ahead and connect the smart plug to your network, and connect
your laptop and the VM to the same network using a bridged networking
configuration.
Next, to find the device we can use the command arp -a, which will
give us the result shown in Figure 8-19.
We can also navigate to the IP address found in the earlier step to see
if there are any interesting web dashboards for this device. In this case, we
can see that there are no files being served over the web server and it is
merely running.
The next step, as for any other pentest, would be to perform a network
scan of the device and discover the different ports that are open and what
services are running.
To scan the smart plug, we use nmap, which is a powerful network
scanner allowing us to see open ports, running services, and also in
specific cases perform additional exploitation. We can install nmap using
sudo apt install nmap and then run a scan using this command:
sudo nmap -sS -T4 192.168.0.253
As we can see from Figure 8-20, a couple of ports are open, including
Port 22 which is running SSH.

aes decrypt python2.7

#!/usr/bin/python

import os, sys, re, socket, time, select, random ,getopt
from Crypto.Cipher import AES

aeskey="fdsl;mewjope456fds4fbvfnjwaugfo"
wiresharkpacket ="packet-data-value".decode("hex")

aesobj = AES.new(aeskey, AES.MODE_ECB)
print str(aesobj.decrypt(wiresharkpacket))

Decrypting XOR Encrypted Data

Listing 7-1. Decrypting XOR Encrypted Data
import os
import sys
key = "key-here".decode("hex")
data = sys.stdin.read()
r = ""
for i in range(len(data)):
c = chr(ord(data[i]) ^ ord(key[i % len(key)]))
r += c
sys.stdout.write(r)

2019年4月10日星期三

Demonstration of read() , write() , and lseek()

Listing 4-3: Demonstration of read() , write() , and lseek()
––––––––––––––––––––––––––––––––––––––––––––––––––––––––– fileio/seek_io.c
#include <sys/stat.h>
#include <fcntl.h>
#include <ctype.h>
#include "tlpi_hdr.h"
int
main(int argc, char *argv[])
{
size_t len;
off_t offset;
int fd, ap, j;
char *buf;
ssize_t numRead, numWritten;
if (argc < 3 || strcmp(argv[1], "--help") == 0)
usageErr("%s file {r<length>|R<length>|w<string>|s<offset>}...\n",
argv[0]);
fd = open(argv[1], O_RDWR | O_CREAT,
S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP |
S_IROTH | S_IWOTH); /* rw-rw-rw- */
if (fd == -1)
errExit("open");
for (ap = 2; ap < argc; ap++) {
switch (argv[ap][0]) {
case 'r': /* Display bytes at current offset, as text */
case 'R': /* Display bytes at current offset, in hex */
len = getLong(&argv[ap][1], GN_ANY_BASE, argv[ap]);
File I/O: The Universal I/O Model 85
buf = malloc(len);
if (buf == NULL)
errExit("malloc");
numRead = read(fd, buf, len);
if (numRead == -1)
errExit("read");
if (numRead == 0) {
printf("%s: end-of-file\n", argv[ap]);
} else {
printf("%s: ", argv[ap]);
for (j = 0; j < numRead; j++) {
if (argv[ap][0] == 'r')
printf("%c", isprint((unsigned char) buf[j]) ?
buf[j] : '?');
else
printf("%02x ", (unsigned int) buf[j]);
}
printf("\n");
}
free(buf);
break;
case 'w': /* Write string at current offset */
numWritten = write(fd, &argv[ap][1], strlen(&argv[ap][1]));
if (numWritten == -1)
errExit("write");
printf("%s: wrote %ld bytes\n", argv[ap], (long) numWritten);
break;
case 's': /* Change file offset */
offset = getLong(&argv[ap][1], GN_ANY_BASE, argv[ap]);
if (lseek(fd, offset, SEEK_SET) == -1)
errExit("lseek");
printf("%s: seek succeeded\n", argv[ap]);
break;
default:
cmdLineErr("Argument must start with [rRws]: %s\n", argv[ap]);
}
}
exit(EXIT_SUCCESS);
}
––––––––––––––––––––––––––––––––––––––––––––––––––––––––– fileio/seek_io.c
list all the
components   ------------> prepare an architecture diagram------------>Label the components and                                                                                                                          communication
                                                                                                                         |                                                                                                                                                                   |                                                                                                                                                                   |                                                                                                                                                                  \/                                                                                                                                                  Identify attack vectors
                                                          Rate the attack    <-------------for each component                                                                                     vectors                                                                                     

The following are the steps required to create an attack surface map of
any given IoT device:
• List all the components present in the target product.
• Prepare an architecture diagram.
• Label the components and the communication flows
between them.
• Identify attack vectors for each component and the
communication channel or protocol used.
• Categorize the attack vectors based on the varying
criticality.

These components involve many vulnerabilities

These components involve many vulnerabilities, some of which are
listed here.
• Firmware
• Ability to modify firmware.
• Insecure signature and integrity verification.
• Hard-coded sensitive values in the firmware—API
keys, passwords, staging URLs, and so on.
• Private certificates.
• Ability to understand the entire functionality of the
device through the firmware.
• File system extraction from the firmware.
• Outdated components with known vulnerabilities.
• Mobile applications
• Reverse engineering the mobile app.
• Dumping source code of the mobile app.
• Insecure authentication and authorization checks.
• Business and logic flaws.
• Side channel data leakage.
• Runtime manipulation attacks.
• Insecure network communication.
• Outdated third-party libraries and software
development kits (SDKs).

Web application
• Client-side injection.
• Insecure direct object reference.
• Insecure authentication and authorization.
• Sensitive data leakage.
• Business logic flaws.
• Cross-site request forgery.
• Cross-site scripting.
That list is just a sample of some of the vulnerabilities present in these
components, which should give you an idea of the kind of vulnerabilities
that affect these components.