#include <stdio.h>
#include <string.h>
#include <openssl/md5.h>
#include "radius.h"
#include "radius_local.h"
int
radius_encrypt_user_password_attr(void *cipher, size_t * clen,
const char *plain, const void *ra, const char *secret)
{
size_t plen = strlen(plain);
size_t slen = strlen(secret);
char b[16], p[16], *c;
size_t off;
MD5_CTX ctx;
unsigned int i;
if (*clen < ROUNDUP(plen, 16))
return (-1);
for (off = 0; off < plen; off += sizeof(p)) {
c = ((char *)cipher) + off;
memset(p, 0, sizeof(p));
strncpy(p, plain + off, sizeof(p));
MD5_Init(&ctx);
MD5_Update(&ctx, secret, slen);
if (off == 0)
MD5_Update(&ctx, ra, 16);
else
MD5_Update(&ctx, c - 16, 16);
MD5_Final(b, &ctx);
for (i = 0; i < 16; i++)
c[i] = p[i] ^ b[i];
}
*clen = off;
return (0);
}
int
radius_decrypt_user_password_attr(char *plain, size_t plen, const void *cipher,
size_t clen, const void *ra, const char *secret)
{
size_t slen = strlen(secret);
char b[16];
size_t off;
char *p, *c;
MD5_CTX ctx;
unsigned int i;
if (clen % 16 != 0)
return (-1);
if (plen < clen + 1)
return (-1);
for (off = 0; off < clen; off += 16) {
c = ((char *)cipher) + off;
p = plain + off;
MD5_Init(&ctx);
MD5_Update(&ctx, secret, slen);
if (off == 0)
MD5_Update(&ctx, ra, 16);
else
MD5_Update(&ctx, c - 16, 16);
MD5_Final(b, &ctx);
for (i = 0; i < 16; i++)
p[i] = c[i] ^ b[i];
}
p = memchr(plain, '\0', off);
if (p == NULL)
plain[off] = '\0';
else {
for (p++; p < plain + off; p++) {
if (*p != '\0')
return (-1);
}
}
return (0);
}
int
radius_get_user_password_attr(const RADIUS_PACKET * packet, char *buf,
size_t len, const char *secret)
{
char cipher[256];
size_t clen = sizeof(cipher);
if (radius_get_raw_attr(packet, RADIUS_TYPE_USER_PASSWORD, cipher,
&clen) != 0)
return (-1);
if (radius_decrypt_user_password_attr(buf, len, cipher, clen,
radius_get_authenticator_retval(packet), secret) != 0)
return (-1);
return (0);
}
int
radius_put_user_password_attr(RADIUS_PACKET * packet, const char *buf,
const char *secret)
{
char cipher[256];
size_t clen = sizeof(cipher);
if (radius_encrypt_user_password_attr(cipher, &clen, buf,
radius_get_authenticator_retval(packet), secret) != 0)
return (-1);
if (radius_put_raw_attr(packet, RADIUS_TYPE_USER_PASSWORD, cipher,
clen) != 0)
return (-1);
return (0);
}