Skip to content

Commit 6591d9f

Browse files
committed
chg: [client core] add logging + check server cert + fix TLS connection
1 parent f9073ed commit 6591d9f

File tree

4 files changed

+49
-41
lines changed

4 files changed

+49
-41
lines changed

conf.sample/destination

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
127.0.0.1:4443
1+
stdout

conf.sample/type

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
8
1+
1

conf.sample/uuid

Lines changed: 0 additions & 1 deletion
This file was deleted.

d4-pyclient.py

Lines changed: 47 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -19,8 +19,8 @@
1919
import datetime
2020

2121
import logging
22-
import logging.handlers
23-
# # TODO: replace print by logger
22+
23+
logger = logging.getLogger('d4-pyclient')
2424

2525
def generate_uuid(filename):
2626
sensor_uuid = str(uuid.uuid4())
@@ -63,8 +63,6 @@ def pack_d4_data(version, type, sensor_uuid, hmac_key, data, destination):
6363
d4_header = create_d4_header(version, type, sensor_uuid, hmac_key, data)
6464
d4_data = d4_header + data
6565

66-
print(data)
67-
6866
# Send data
6967
send_d4_data(destination, d4_data)
7068

@@ -77,7 +75,8 @@ def send_d4_data(destination, d4_data):
7775

7876
def get_config_from_file(filename, r_type='str'):
7977
if not os.path.isfile(filename):
80-
print('error config file not found')
78+
logger.error('config file not found: {}'.format(filename))
79+
sys.exit(1)
8180

8281
with open(filename, 'r') as f:
8382
config = f.read()
@@ -88,7 +87,8 @@ def get_config_from_file(filename, r_type='str'):
8887
try:
8988
config = int(config)
9089
except:
91-
print('error config file, invalid type')
90+
logger.error('config file: {}, invalid type'.format(filename))
91+
sys.exit(1)
9292
else:
9393
config = config.encode()
9494
return config
@@ -107,7 +107,8 @@ def get_sensor_uuid(config_dir):
107107

108108
def load_config(config_dir):
109109
if not os.path.isdir(config_dir):
110-
print('error config file not found')
110+
logger.error('This config directory is invalid: {},'.format(filename))
111+
sys.exit(1)
111112

112113
# HMAC Key
113114
dict_config = {}
@@ -117,26 +118,30 @@ def load_config(config_dir):
117118
filename = os.path.join(config_dir, 'type')
118119
dict_config['type'] = get_config_from_file(filename, r_type='int')
119120
if dict_config['type'] < 0 and dict_config['type'] > 255:
120-
print('error, unsuported type')
121+
logger.error('unsuported d4 type: {}'.format(dict_config['type']))
122+
sys.exit(1)
121123

122124
filename = os.path.join(config_dir, 'version')
123125
dict_config['version'] = get_config_from_file(filename, r_type='int')
124126
if dict_config['version'] < 0:
125-
print('error, unsuported type')
127+
logger.error('invalid version: {}'.format(dict_config['version']))
128+
sys.exit(1)
126129

127130
filename = os.path.join(config_dir, 'snaplen')
128131
dict_config['snaplen'] = get_config_from_file(filename, r_type='int')
129-
if dict_config['snaplen'] < 0:
130-
print('error, unsuported type')
132+
if dict_config['snaplen'] <= 0:
133+
logger.error('invalid snaplen')
134+
sys.exit(1)
131135

132136
# Sensor UUID
133137
dict_config['uuid'] = get_sensor_uuid(config_dir)
134138
return dict_config
135139

136-
def get_destination(config_dir, verify_cert=True):
140+
def get_destination(config_dir, check_certificate=True):
137141
filename = os.path.join(config_dir, 'destination')
138142
if not os.path.isfile(filename):
139-
print('error destination file not found')
143+
logger.error('destination file not found: {}'.format(filename))
144+
sys.exit(1)
140145

141146
with open(filename, 'r') as f:
142147
destination = f.read().replace('\n', '')
@@ -147,13 +152,15 @@ def get_destination(config_dir, verify_cert=True):
147152
else:
148153
if not ':' in destination:
149154
# port = 80 ?
150-
print('error, destination')
155+
logger.error('The destination is invalid')
156+
sys.exit(1)
151157
host, port = destination.rsplit(':', 1)
152158
# verify port
153159
try:
154160
port = int(port)
155161
except:
156-
print('error, invalid port')
162+
logger.error('Invalid port')
163+
sys.exit(1)
157164
# verify address
158165
try:
159166
host = str(ipaddress.ip_address(host))
@@ -163,8 +170,8 @@ def get_destination(config_dir, verify_cert=True):
163170
try:
164171
host = socket.gethostbyname(host)
165172
except:
166-
print('Destination Host: Name or service not known')
167-
print(host)
173+
logger.error('Destination Host: Name or service not known')
174+
sys.exit(1)
168175

169176
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
170177
# TCP Keepalive
@@ -173,11 +180,8 @@ def get_destination(config_dir, verify_cert=True):
173180
s.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, 15)
174181
s.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, 15)
175182

176-
## TODO: add flag
177-
verify_cert = False
178-
179183
# SSL
180-
if verify_cert:
184+
if check_certificate:
181185
cert_reqs_option = ssl.CERT_REQUIRED
182186
else:
183187
cert_reqs_option = ssl.CERT_NONE
@@ -187,39 +191,34 @@ def get_destination(config_dir, verify_cert=True):
187191
try:
188192
client_socket.connect((host, port))
189193
except ConnectionRefusedError:
190-
print('error, Connection to {}:{} refused'.format(host, port))
194+
logger.error('Connection to {}:{} refused'.format(host, port))
191195
sys.exit(1)
192196
except ssl.SSLError as e:
193-
print(e)
197+
logger.error(e)
194198
sys.exit(1)
195199
return client_socket
196200

197201

198202
def get_metaheader_json(config_dir):
199203
filename = os.path.join(config_dir, 'metaheader.json')
200204
if not os.path.isfile(filename):
201-
print('error metaheader file not found')
205+
logger.error('Metaheader file not found: {}'.format(filename))
206+
sys.exit(1)
202207

203208
with open(filename, 'rb') as f:
204209
metaheader = f.read()
205210
try:
206211
metaheader = json.loads(metaheader)
207212
except:
208-
print('error, invalid json file')
213+
logger.error('The JSON file is invalid')
214+
sys.exit(1)
209215
return json.dumps(metaheader).encode()
210216

211-
if __name__ == "__main__":
212-
parser = argparse.ArgumentParser()
213-
parser.add_argument('-c', '--config' ,help='config_directory' ,type=str, dest='config', required=True)
214-
args = parser.parse_args()
215-
config_dir = args.config
216-
217+
def read_and_send_data(config_dir, check_certificate):
217218
config = load_config(config_dir)
218-
destination = get_destination(config_dir)
219+
destination = get_destination(config_dir, check_certificate=check_certificate)
219220

220221
buffer = b''
221-
# config['type'] = 2
222-
config['snaplen'] = 64
223222

224223
# handle extended type
225224
if config['type'] == 2 or config['type'] == 254:
@@ -234,18 +233,28 @@ def get_metaheader_json(config_dir):
234233
try:
235234
for data in io.open(sys.stdin.fileno(), mode='rb', buffering=0):
236235

237-
print(data)
238-
239236
if data:
240237
buffer = buffer + data
241238
buffer = prepare_data(config['version'], config['type'], config['uuid'], config['key'], config['snaplen'], buffer, destination)
242239

243240
pack_d4_data(config['version'], config['type'], config['uuid'], config['key'], buffer, destination)
244-
destination.close()
241+
if not isinstance(destination, str):
242+
destination.shutdown(socket.SHUT_RDWR)
245243

246244
# Send buffer content
247245
except KeyboardInterrupt:
248246
# Pack data
249247
buffer = prepare_data(config['version'], config['type'], config['uuid'], config['key'], config['snaplen'], buffer, destination)
250248
pack_d4_data(config['version'], config['type'], config['uuid'], config['key'], buffer, destination)
251-
destination.close()
249+
if not isinstance(destination, str):
250+
destination.shutdown(socket.SHUT_RDWR)
251+
252+
if __name__ == "__main__":
253+
parser = argparse.ArgumentParser()
254+
parser.add_argument('-c', '--config' ,help='config directory' ,type=str, dest='config', required=True)
255+
parser.add_argument('-cc', '--check_certificate' ,help='check server certificate', action="store_true")
256+
args = parser.parse_args()
257+
config_dir = args.config
258+
check_certificate = args.check_certificate
259+
260+
read_and_send_data(config_dir, check_certificate)

0 commit comments

Comments
 (0)