为每个请求创建一个自定义apache模块钩子?

时间:2017-02-19 13:44:19

标签: c apache module hmac

对于一个项目,我需要在apache级别进行HMAC身份验证。所以我将mod_example解释为here到目前为止:

module AP_MODULE_DECLARE_DATA   hmac_module =
        {
                STANDARD20_MODULE_STUFF,
                NULL,            // Per-directory configuration handler
                NULL,            // Merge handler for per-directory configurations
                NULL,            // Per-server configuration handler
                NULL,            // Merge handler for per-server configurations
                NULL,            // Any directives we may have for httpd
                register_hooks   // Our hook registering function
        };


/* register_hooks: Adds a hook to the httpd process */
static void register_hooks(apr_pool_t *pool)
{

    /* Hook the request handler */
    ap_hook_handler(hmac_handler, NULL, NULL,APR_HOOK_REALLY_FIRST);
}

static int hmac_handler(request_rec *r)
{
    // ...
    // some variable definition
    // ...

    // Check that the "hmac-handler" handler is being called.
    if (!r->handler || strcmp(r->handler, "hmac-handler")) return (DECLINED);

    ap_args_to_table(r, &GET);
    ap_parse_form_data(r, NULL, &POST, -1, 8192);

    timestamp = apr_table_get(r->headers_in, "X-EPOCH");
    claimedHash = apr_table_get(r->headers_in, "X-HMAC");
    if (!timestamp){
        ap_log_rerror(APLOG_MARK,APLOG_ERR,HTTP_FORBIDDEN,r,"Timestamp does not exits in request");
        return HTTP_FORBIDDEN;
    }
    if(!claimedHash){
        ap_log_rerror(APLOG_MARK,APLOG_ERR,HTTP_FORBIDDEN,r,"There is no claimed hash in the request!");
        return HTTP_FORBIDDEN;
    }

    //...
    // calculate timestamp's sha1 hash
    //...

    if(strcmp(claimedHash,encoded)){
        ap_log_rerror(APLOG_MARK,APLOG_ERR,HTTP_FORBIDDEN,r,"Claimed hash and digested values does not match,Claimed:%s , Target:%s",claimedHash,encoded);
        return HTTP_FORBIDDEN;
    }

    // Let Apache know that we responded to this request.
    return OK;
}

现在,我需要在进一步处理之前将此模块挂钩到apache中,以便检查此请求是否经过身份验证。

我知道APR_HOOK_REALLY_FIRST函数中的ap_hook_handler参数使apache在任何其他处理程序之前执行此处理程序。

但我需要知道如何在特定目录中发生的任何请求之前执行此处理程序。

1 个答案:

答案 0 :(得分:1)

我终于把它弄清楚了。我不应该在处理阶段注册挂钩,而应该在早期阶段注册我的模块:access_checker。

如果有人有兴趣,最终代码可在github获得。