kerberosTest/sample/server.py

60 lines
1.7 KiB
Python
Raw Normal View History

2022-07-28 14:47:57 +00:00
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import gssapi
import sys
import subprocess
2022-07-30 13:19:32 +00:00
import socket
s = socket.socket()
def send_data(cli:socket, data:bytes, length:int):
cli.send(length.to_bytes(3, byteorder="little", signed=True))
cli.send(data)
def recv_data(cli:socket):
bs = cli.recv(3)
length = int.from_bytes(bs, byteorder="little", signed=True)
print(length)
data = cli.recv(length)
return data
2022-07-28 14:47:57 +00:00
# 设置环境变量
2023-10-06 02:31:49 +00:00
principal = "server/hadoop.test.hadoop.com@TEST.HADOOP.COM"
2022-07-28 14:47:57 +00:00
curr_path = os.getcwd()
2023-10-06 02:31:49 +00:00
os.environ["KRB5_CONFIG"] = curr_path + "/krb5.conf"
os.environ["KRB5_KTNAME"] = curr_path + "/hadoop.keytab"
os.environ["KRB5CCNAME"] = "/tmp/krb5_server_1000"
2022-07-28 14:47:57 +00:00
os.environ["KRB5_TRACE"] = "/tmp/server.log"
kinit_res = subprocess.call(["kinit", "-kt", os.environ["KRB5_KTNAME"], principal])
klist_res = subprocess.call(["klist"])
2023-10-06 02:31:49 +00:00
name = gssapi.Name("server/hadoop.test.hadoop.com", name_type=gssapi.NameType.kerberos_principal)
2022-07-28 14:47:57 +00:00
cname = name.canonicalize(gssapi.MechType.kerberos)
print(cname)
host = "127.0.0.1"
port = 12345
s.bind((host, port))
s.listen(1000)
creds = gssapi.Credentials(usage="accept", name=cname)
server_ctx = gssapi.SecurityContext(creds=creds, usage="accept")
print(server_ctx)
while True:
c, addr = s.accept()
print("client")
c.send(b"no_auth")
2022-07-30 13:19:32 +00:00
while not server_ctx.complete:
client_ticket = recv_data(c)
print("client_ticket=", client_ticket, "len=", len(client_ticket), "\n")
server_token = server_ctx.step(client_ticket)
print("server_token=", server_token, "len=", len(server_token), "\n")
send_data(c, server_token, len(server_token))
print("auth ok")
2022-07-28 14:47:57 +00:00