kerberosTest/sample/sample-client.c
2022-03-20 22:14:30 +08:00

142 lines
2.8 KiB
C

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sasl/sasl.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <linux/in.h>
#include <string.h>
#define SAMPLE_SEC_BUF_SIZE (2048)
char buf[SAMPLE_SEC_BUF_SIZE];
static sasl_conn_t *conn = NULL;
const char *realm = "DOMAIN.COM";
const char *mech = "GSSAPI";
const char *iplocal = "127.0.0.1";
const char *ipremote = "127.0.0.1";
char *searchpath = NULL;
const char *service = "zeekling";
const char *fqdn = "";
int cfd;
int init_sasl() {
int result = sasl_client_init(NULL);
if (result != SASL_OK) {
printf("Initializing libsasl\n");
return -1;
}
return 0;
}
int connect_server() {
struct sockaddr_in s_add, c_add;
unsigned short portnum = 2345;
printf("Hello,welcome to client !\n");
cfd = socket(AF_INET, SOCK_STREAM, 0);
if(-1 == cfd) {
printf("socket fail ! \n");
return 1;
}
printf("socket ok !\n");
bzero(&s_add, sizeof(struct sockaddr_in));
s_add.sin_family = AF_INET;
s_add.sin_addr.s_addr = inet_addr("127.0.0.1");
s_add.sin_port = htons(portnum);
if(-1 == connect(cfd,(struct sockaddr *)(&s_add), sizeof(struct sockaddr))) {
printf("connect fail !\n");
return 1;
}
printf("connect ok !\n");
return 0;
}
int auth_sever() {
int result = sasl_client_new("sample", fqdn, "127.0.0.1",
"127.0.0.1", NULL, 0, &conn);
if (result != SASL_OK) {
printf("client new client failed\n");
return 1;
}
char *data = NULL;
unsigned len = 0;
result = sasl_client_start(conn, mech, NULL, &data, &len, &mech);
if (result != SASL_OK && result != SASL_CONTINUE) {
printf("client auth start failed error:%s\n", sasl_errdetail(conn));
return 1;
}
while (1) {
//todo 多次认证
printf("write data %s, %d", data, len);
if(-1 == write(cfd, data, len)) {
printf("write failed\n");
return 1;
}
int recbytes = 0;
char *buffer = NULL;
if (read(recbytes = read(cfd, buffer, 1024)) == -1) {
printf("read error\n");
return 1;
}
printf("receive %s %d", buffer, recbytes);
result = sasl_client_step(conn, buffer, recbytes, NULL, &data, &len);
if (result != SASL_OK && result != SASL_CONTINUE) {
printf("auth failed, %s\n", sasl_errdetail(conn));
return 1;
}
}
return 0;
}
int main() {
int result;
const char *data;
const char *chosenmech;
int serverlast = 0;
unsigned len;
char *userid = NULL;
char *authid = NULL;
int recbytes;
int sin_size;
char buffer[1024]={0};
if (connect_server() != 0)
{
return 1;
}
if (init_sasl() != 0) {
return 1;
}
if(-1 == (recbytes = read(cfd, buffer, 1024))) {
printf("read data fail !\n");
return -1;
}
if (strcmp(buffer, "need_auth") == 0 && auth_sever() != 0) {
printf("auth failed\n");
return -1;
}
printf("auth ok\nREC:\n");
buffer[recbytes]='\0';
printf("%s\n",buffer);
auth_sever();
getchar();
close(cfd);
if (init_sasl() != 0) {
return 1;
}
return 0;
}