Convert HTPasswd code from Go to C

This commit is contained in:
Arthur Barr
2020-10-01 17:15:37 +01:00
committed by Arthur J Barr
parent adbc95c5d5
commit 5fd9fc5e26
16 changed files with 798 additions and 431 deletions

View File

@@ -0,0 +1,42 @@
# © Copyright IBM Corporation 2017, 2020
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Where to find the sample test.
SRC_DIR = src
# Flags passed to the C compiler.
CFLAGS += -std=c11 -fPIC -Wall
log.o : $(SRC_DIR)/log.c $(SRC_DIR)/log.h
gcc $(CFLAGS) -c $(SRC_DIR)/log.c
htpass.o : $(SRC_DIR)/htpass.c $(SRC_DIR)/htpass.h
gcc $(CFLAGS) -c -I /usr/include/apr-1 $^
htpass_test.o : htpass.o log.o
gcc $(CFLAGS) -I /usr/include/apr-1 -L/usr/lib64 -lapr-1 -laprutil-1 $(SRC_DIR)/htpass_test.c $^ -o htpass_test
htpass_test : htpass_test.o
./htpass_test
mqhtpass.so : log.o htpass.o
gcc $(CFLAGS) -I/opt/mqm/inc -D_REENTRANT -L/usr/lib64 -lapr-1 -laprutil-1 -L/opt/mqm/lib64 -lmqm_r -Wl,-rpath,/opt/mqm/lib64 -Wl,-rpath,/usr/lib64 -shared $(SRC_DIR)/mqhtpass.c $^ -o $@
ldd $@
mqhtpass_unittest.o : $(SRC_DIR)/mqhtpass_test.cc \
$(SRC_DIR)/sample1.h $(FUSED_GTEST_H)
gcc $(CFLAGS) -c $(SRC_DIR)/mqhtpass_test.cc
mqhtpass_unittest : mqhtpass.so mqhtpass_test.o gtest-all.o gtest_main.o
gcc $(CFLAGS) $^ -o $@

View File

@@ -0,0 +1,155 @@
/*
© Copyright IBM Corporation 2020
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include <errno.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "log.h"
#include <linux/limits.h>
#include <apr_general.h>
#include <apr_errno.h>
#include <apr_md5.h>
char * find_hash(char*, char*);
char * find_hash(char *filename, char *user)
{
bool found = false;
FILE *fp;
char *huser;
char *hash;
fp = fopen(filename, "r");
if (fp == NULL)
{
log_errorf("Error %d opening htpasswd file '%s'", errno, filename);
}
if (fp)
{
const size_t line_size = 1024;
char *line = malloc(line_size);
while (fgets(line, line_size, fp) != NULL)
{
huser = strtok(line, ":");
if (strcmp(user, huser) == 0)
{
hash = strtok(NULL, " \r\n\t");
found = true;
break;
}
}
fclose(fp);
// if (line)
// free(line);
// if (huser)
// free(huser);
// if (encPassword)
// free(encPassword);
}
if (!found)
{
hash = NULL;
}
return(hash);
}
bool htpass_authenticate_user(char *filename, char *user, char *password)
{
char *hash = find_hash(filename, user);
bool result = false;
// Use the Apache Portable Runtime utilities to validate the password against the hash.
// Supports multiple hashing algorithms, but we should only be using bcrypt
apr_status_t status = apr_password_validate(password, hash);
// status is usually either APR_SUCCESS or APR_EMISMATCH
if (status == APR_SUCCESS) {
result = true;
log_debugf("Correct password supplied. user=%s", user);
} else {
log_debugf("Incorrect password supplied. user=%s", user);
}
return(result);
}
// bool htpass_authenticate_user(char *filename, char *user, char *password)
// {
// bool result = false;
// FILE *fp;
// // char line[1024];
// char *huser;
// char *hash;
// // size_t len = 0;
// // size_t read;
// // int valid = -1;
// fp = fopen(filename, "r");
// if (fp == NULL)
// {
// log_errorf("Error %d opening htpasswd file '%s'", errno, filename);
// }
// if (fp)
// {
// const size_t line_size = 1024;
// char *line = malloc(line_size);
// while (fgets(line, line_size, fp) != NULL)
// {
// huser = strtok(line, ":");
// if (strcmp(user, huser) == 0)
// {
// hash = strtok(NULL, " \r\n\t");
// log_debugf("Matched user in htpasswd file: user=%s hash=%s*", huser, hash);
// // Use the Apache Portable Runtime utilities to validate the password against the hash.
// // Supports multiple hashing algorithms, but we should only be using bcrypt
// apr_status_t status = apr_password_validate(password, hash);
// // status is usually either APR_SUCCESS or APR_EMISMATCH
// if (status == APR_SUCCESS) {
// result = true;
// log_debugf("Correct password supplied. user=%s", huser);
// } else {
// log_debugf("Incorrect password supplied. user=%s", huser);
// }
// // Break out of the loop, as we've found the right user
// break;
// // TODO: Do we need to free(hash)?
// }
// else
// {
// log_debugf("Read incorrect user in htpassword: user=%s", huser);
// }
// }
// fclose(fp);
// // if (line)
// // free(line);
// // if (huser)
// // free(huser);
// // if (encPassword)
// // free(encPassword);
// }
// return result;
// }
bool htpass_valid_user(char *filename, char *user)
{
char *hash = find_hash(filename, user);
bool valid = false;
if (hash != NULL)
{
valid = true;
}
return(valid);
}

View File

@@ -0,0 +1,23 @@
/*
© Copyright IBM Corporation 2020
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#ifndef _HTPASS_H
#define _HTPASS_H
_Bool htpass_authenticate_user(char *, char *, char *);
_Bool htpass_valid_user(char *, char *);
#endif

View File

@@ -0,0 +1,71 @@
/*
© Copyright IBM Corporation 2020
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include <stdio.h>
#include <stdlib.h>
#include "log.h"
#include "htpass.h"
void test_fail(const char *test_name) {
printf("Failed test %s\n", test_name);
exit(1);
}
void test_htpass_authenticate_user_fred_valid()
{
int ok = htpass_authenticate_user("./src/htpass_test.htpasswd", "fred", "passw0rd");
printf("%s: fred - %d\n", __func__, ok);
if (!ok) test_fail(__func__);
}
void test_htpass_authenticate_user_fred_invalid1()
{
int ok = htpass_authenticate_user("./src/htpass_test.htpasswd", "fred", "passw0rd ");
printf("%s: fred - %d\n", __func__, ok);
if (ok) test_fail(__func__);
}
void test_htpass_authenticate_user_fred_invalid2()
{
int ok = htpass_authenticate_user("./src/htpass_test.htpasswd", "fred", "");
printf("%s: fred - %d\n", __func__, ok);
if (ok) test_fail(__func__);
}
void test_htpass_authenticate_user_fred_invalid3()
{
int ok = htpass_authenticate_user("./src/htpass_test.htpasswd", "fred", "clearlywrong");
printf("%s: fred - %d\n", __func__, ok);
if (ok) test_fail(__func__);
}
void test_htpass_authenticate_user_barney_valid()
{
int ok = htpass_authenticate_user("./src/htpass_test.htpasswd", "barney", "s3cret");
printf("%s: barney - %d\n", __func__, ok);
if (!ok) test_fail(__func__);
}
int main()
{
log_init_file(stdout);
printf("TESTING BEGINS\n");
test_htpass_authenticate_user_fred_valid();
test_htpass_authenticate_user_fred_invalid1();
test_htpass_authenticate_user_fred_invalid2();
test_htpass_authenticate_user_fred_invalid3();
test_htpass_authenticate_user_barney_valid();
}

View File

@@ -0,0 +1,2 @@
fred:$2y$05$3Fp9epsqEwWOHdyj9Ngf9.qfX34kzc9zNrdQ7kac0GmcCvQjIkAwy
barney:$2y$05$l8EoyCQ9y2PyfUzIDDfTyu7SSaJEYB1TuHy07xZvN7xt/pR3SIw0a

View File

@@ -0,0 +1,166 @@
/*
© Copyright IBM Corporation 2020
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include <stdio.h>
#include <stdarg.h>
#include <time.h>
#include <sys/time.h>
#include <unistd.h>
#define LOG_LEVEL_INFO 0
#define LOG_LEVEL_ERROR 1
#define LOG_LEVEL_DEBUG 2
FILE *fp = NULL;
int pid;
int log_init(char *filename)
{
int result = 0;
pid = getpid();
if (!fp)
{
fp = fopen(filename, "a");
if (fp)
{
setbuf(fp, NULL);
}
else
{
result = 1;
}
}
return result;
}
void log_init_file(FILE *f)
{
fp = f;
}
void log_close()
{
if (fp)
{
fclose(fp);
fp = NULL;
}
}
void log_printf(const char *source_file, int source_line, const char *level, const char *format, ...)
{
if (fp)
{
char buff[70];
struct tm *utc;
time_t t;
struct timeval now;
gettimeofday(&now, NULL);
t = now.tv_sec;
t = time(NULL);
utc = gmtime(&t);
fprintf(fp, "{");
fprintf(fp, "\"loglevel\":\"%s\"", level);
// Print ISO-8601 time and date
if (strftime(buff, sizeof buff, "%FT%T", utc))
{
fprintf(fp, ", \"ibm_datetime\":\"%s.%3ld", buff, now.tv_usec);
}
fprintf(fp, ", \"ibm_processId\":\"%d\"", pid);
fprintf(fp, ", \"module\":\"%s:%d\"", source_file, source_line);
fprintf(fp, ", \"message\":\"");
// Print log message, using varargs
va_list args;
va_start(args, format);
vfprintf(fp, format, args);
va_end(args);
fprintf(fp, "\"}\n");
}
}
/**
* Writes a message to the log file, using the specified type, based on a printf format string.
*/
// void log_printf(const char *level, const char *format, va_list args)
// {
// // FindSize();
// if (fp)
// {
// char buff[70];
// struct tm *utc;
// time_t t;
// struct timeval now;
// gettimeofday(&now, NULL);
// t = now.tv_sec;
// // Print ISO-8601 time and date
// t = time(NULL);
// utc = gmtime(&t);
// fprintf(fp, "{");
// fprintf(fp, "\"loglevel\":\"%s\"", level);
// if (strftime(buff, sizeof buff, "%FT%T", utc))
// {
// fprintf(fp, ", \"ibm_datetime\":\"%s.%3ld", buff, now.tv_usec);
// }
// fprintf(fp, ", \"ibm_processId\": \"%d\"", pid);
// fprintf(fp, ", \"message\":\"");
// // Print log message, using varargs
// // va_list args;
// // va_start(args, format);
// vfprintf(fp, format, args);
// // va_end(args);
// fprintf(fp, "\"}\n");
// }
// }
// void log_errorf(const char *format, ...)
// {
// va_list args;
// va_start(args, format);
// log_printf("ERROR", format, args);
// va_end(args);
// }
// void log_infof(const char *format, ...)
// {
// va_list args;
// va_start(args, format);
// log_printf("INFO", format, args);
// va_end(args);
// }
// void log_debugf(const char *format, ...)
// {
// va_list args;
// va_start(args, format);
// log_printf("DEBUG", format, args);
// va_end(args);
// }
// void log_debugf2(const char *source_file, const char *source_line, const char *format, ...)
// {
// va_list args;
// va_start(args, format);
// log_printf(source_line, format, args);
// va_end(args);
// }

View File

@@ -0,0 +1,50 @@
/*
© Copyright IBM Corporation 2020
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#ifndef _LOG_H
#define _LOG_H
int log_init(char *);
/**
* Initialize the log wih an existing file handle
*/
void log_init_file(FILE *);
/**
* Write a message to the log file, based on a printf format string.
*/
void log_printf(const char*, int, const char*, const char*, ...);
void log_close();
/**
* Variadic macro to write an informational message to the log file, based on a printf format string.
*/
#define log_infof(format,...) log_printf(__FILE__, __LINE__, "INFO", format, ##__VA_ARGS__)
/**
* Variadic macro to write an error message to the log file, based on a printf format string.
*/
#define log_errorf(format,...) log_printf(__FILE__, __LINE__, "ERROR", format, ##__VA_ARGS__)
/**
* Variadic macro to write a debug message to the log file, based on a printf format string.
*/
#define log_debugf(format,...) log_printf(__FILE__, __LINE__, "DEBUG", format, ##__VA_ARGS__)
#endif

View File

@@ -0,0 +1,262 @@
/*
© Copyright IBM Corporation 2020
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// This is a developer only configuration and not recommended for production usage.
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <cmqec.h>
#include "log.h"
#include "htpass.h"
/****************************************************************************/
/* Declare the internal functions that implement the interface */
/****************************************************************************/
MQZ_INIT_AUTHORITY MQStart;
static MQZ_AUTHENTICATE_USER mqhtpass_authenticate_user;
static MQZ_FREE_USER mqhtpass_free_user;
static MQZ_TERM_AUTHORITY mqhtpass_term_auth;
#define LOG_FILE "/var/mqm/errors/mqhtpass.log"
#define HTPASSWD_FILE "/etc/mqm/mq.htpasswd"
static char *trim(char *s);
/**
* Initialization and entrypoint for the dynamically loaded
* authorization installable service. It registers the addresses of the
* other functions which are to be called by the queue manager.
*
* This function is called whenever the module is loaded. The Options
* field will show whether it's a PRIMARY (i.e. during qmgr startup) or
* SECONDARY (any other time - normally during the start of an agent
* process which is not necessarily the same as during MQCONN, especially
* when running multi-threaded agents) initialization, but there's
* nothing different that we'd want to do here based on that flag.
*
* Because of when the init function is called, there is no need to
* worry about multi-threaded stuff in this particular function.
*/
void MQENTRY MQStart(
MQHCONFIG hc,
MQLONG Options,
MQCHAR48 QMgrName,
MQLONG ComponentDataLength,
PMQBYTE ComponentData,
PMQLONG Version,
PMQLONG pCompCode,
PMQLONG pReason)
{
MQLONG CC = MQCC_OK;
MQLONG Reason = MQRC_NONE;
CC = log_init(LOG_FILE);
if (CC == MQCC_OK)
{
log_infof("MQStart options=%s qmgr=%s", ((Options == MQZIO_SECONDARY) ? "Secondary" : "Primary"), trim(QMgrName));
}
/************************************************************************/
/* Initialize the entry point vectors. This is performed for both */
/* global and process initialisation, i.e whatever the value of the */
/* Options field. */
/************************************************************************/
if (CC == MQCC_OK)
hc->MQZEP_Call(hc, MQZID_INIT_AUTHORITY, (PMQFUNC)MQStart, &CC, &Reason);
if (CC == MQCC_OK)
hc->MQZEP_Call(hc, MQZID_TERM_AUTHORITY, (PMQFUNC)mqhtpass_term_auth, &CC, &Reason);
if (CC == MQCC_OK)
hc->MQZEP_Call(hc, MQZID_AUTHENTICATE_USER, (PMQFUNC)mqhtpass_authenticate_user, &CC, &Reason);
if (CC == MQCC_OK)
hc->MQZEP_Call(hc, MQZID_FREE_USER, (PMQFUNC)mqhtpass_free_user, &CC, &Reason);
*Version = MQZAS_VERSION_5;
*pCompCode = CC;
*pReason = Reason;
return;
}
/**
* Called during the connection of any application. This allows the OAM
* to change the userid associated with the connection, regardless of the
* operating system user ID. One reason you might want to do that is to
* deal with non-standard user IDs, which perhaps are longer than 12
* characters. The CorrelationPtr can be assigned in this function to
* point to some OAM-managed storage, and is available as part of the
* MQZED structure for all subsequent functions. Note that there is only
* one CorrelPtr stored for the user's hconn, so if two OAMs are chained
* and both want to manage storage for the connection, there would be
* difficulties as there is no reverse call that would allow the second
* to reset the first's pointer (or vice versa). I'd suggest instead
* using something like thread-specific storage as each thread is tied
* to the hconn.
*
* When a clntconn/svrconn channel connects to the queue manager, the
* authentication is supposed to take two stages. First as the
* channel program connects, and then as the MCAUSER is set. You will
* see this as "initial" and "change" context values in the parameters.
*/
static void MQENTRY mqhtpass_authenticate_user(
PMQCHAR pQMgrName,
PMQCSP pSecurityParms,
PMQZAC pApplicationContext,
PMQZIC pIdentityContext,
PMQPTR pCorrelationPtr,
PMQBYTE pComponentData,
PMQLONG pContinuation,
PMQLONG pCompCode,
PMQLONG pReason)
{
char *spuser = NULL;
char *sppass = NULL;
if ((pSecurityParms->AuthenticationType) == MQCSP_AUTH_USER_ID_AND_PWD)
{
// Authenticating a user ID and password.
// Firstly, create null-terminated strings from the user credentials in the MQ CSP object
spuser = malloc(pSecurityParms->CSPUserIdLength + 1);
strncpy(spuser, pSecurityParms->CSPUserIdPtr, pSecurityParms->CSPUserIdLength);
spuser[pSecurityParms->CSPUserIdLength] = 0;
sppass = malloc(pSecurityParms->CSPPasswordLength + 1);
strncpy(sppass, pSecurityParms->CSPPasswordPtr, pSecurityParms->CSPPasswordLength);
sppass[pSecurityParms->CSPPasswordLength] = 0;
log_debugf("%s with CSP user set. user=%s", __func__, spuser);
bool authenticated = htpass_authenticate_user(HTPASSWD_FILE, spuser, sppass);
if (authenticated)
{
*pCompCode = MQCC_OK;
*pReason = MQRC_NONE;
*pContinuation = MQZCI_CONTINUE;
memcpy(pIdentityContext->UserIdentifier, spuser, sizeof(pIdentityContext->UserIdentifier));
log_debugf("Authenticated user=%s", pIdentityContext->UserIdentifier);
}
else
{
// Return a warning, which indicates to MQ that this authorization service hasn't
// authenticated the user, but other authorization services should be tried as well.
*pCompCode = MQCC_WARNING;
*pReason = MQRC_NONE;
*pContinuation = MQZCI_CONTINUE;
log_debugf(
"Failed to authenticate user=%s effuser=%s applname=%s cspuser=%s cc=%d reason=%d",
pIdentityContext->UserIdentifier,
pApplicationContext->EffectiveUserID,
pApplicationContext->ApplName,
spuser,
*pCompCode,
*pReason);
}
free(spuser);
free(sppass);
}
else
{
// Password not supplied, so just check that the user ID is valid
spuser = malloc(sizeof(PMQCHAR12));
strncpy(spuser, pApplicationContext->EffectiveUserID, strlen(pApplicationContext->EffectiveUserID));
spuser[sizeof(PMQCHAR12)] = 0;
log_debugf("%s without CSP user set. effectiveuid=%s", __func__, spuser);
bool valid_user = htpass_valid_user(HTPASSWD_FILE, spuser);
if (valid_user)
{
*pCompCode = MQCC_OK;
*pReason = MQRC_NONE;
*pContinuation = MQZCI_CONTINUE;
memcpy(pIdentityContext->UserIdentifier, spuser, sizeof(pIdentityContext->UserIdentifier));
}
else
{
*pCompCode = MQCC_WARNING;
*pReason = MQRC_NONE;
*pContinuation = MQZCI_CONTINUE;
log_debugf(
"Invalid user=%s effuser=%s applname=%s cspuser=%s cc=%d reason=%d",
pIdentityContext->UserIdentifier,
pApplicationContext->EffectiveUserID,
pApplicationContext->ApplName,
spuser,
*pCompCode,
*pReason);
}
}
return;
}
/**
* Called during MQDISC, as the inverse of the Authenticate. If the authorization
* service has allocated private storage to hold additional information about
* the user, then this is the time to free it. No more calls will be made
* to the authorization service for this connection instance of this user.
*/
static void MQENTRY mqhtpass_free_user(
PMQCHAR pQMgrName,
PMQZFP pFreeParms,
PMQBYTE pComponentData,
PMQLONG pContinuation,
PMQLONG pCompCode,
PMQLONG pReason)
{
log_infof("mqhtpass_freeuser()");
*pCompCode = MQCC_WARNING;
*pReason = MQRC_NONE;
*pContinuation = MQZCI_CONTINUE;
}
/**
* Called during MQDISC, as the inverse of the Authenticate. If the OAM
* has allocated private storage to hold additional information about
* the user, then this is the time to free it. No more calls will be made
* to the authorization service for this connection instance of this user.
*/
static void MQENTRY mqhtpass_term_auth(
MQHCONFIG hc,
MQLONG Options,
PMQCHAR pQMgrName,
PMQBYTE pComponentData,
PMQLONG pCompCode,
PMQLONG pReason)
{
log_infof("mqhtpass_term_auth()");
if ((Options & MQZTO_PRIMARY) == MQZTO_PRIMARY)
{
log_close();
}
*pCompCode = MQCC_OK;
*pReason = MQRC_NONE;
}
/**
* Remove trailing spaces from a string.
*/
static char *trim(char *s)
{
int i;
for (i = strlen(s) - 1; i >= 0; i--)
{
if (s[i] == ' ')
s[i] = 0;
else
break;
}
return s;
}