tsig_python.cc 12.5 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
// Copyright (C) 2011  Internet Systems Consortium, Inc. ("ISC")
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.

15
16
17
18
19
20
21
22
23
24
#define PY_SSIZE_T_CLEAN        // need for "y#" below
#include <Python.h>

#include <string>
#include <stdexcept>

#include <exceptions/exceptions.h>

#include <util/python/pycppwrapper_util.h>

25
26
#include <dns/tsig.h>

27
28
29
30
31
32
33
34
35
36
#include "pydnspp_common.h"
#include "name_python.h"
#include "tsigkey_python.h"
#include "tsigerror_python.h"
#include "tsigrecord_python.h"
#include "tsig_python.h"

using namespace std;
using namespace isc;
using namespace isc::util::python;
37
using namespace isc::dns;
38
using namespace isc::dns::python;
39
40
41
42
43
44

// For each class, we need a struct, a helper functions (init, destroy,
// and static wrappers around the methods we export), a list of methods,
// and a type description

namespace {
45
46
47
48
49
50
51
// The s_* Class simply covers one instantiation of the object
class s_TSIGContext : public PyObject {
public:
    s_TSIGContext() : cppobj(NULL) {};
    TSIGContext* cppobj;
};

52
53
// Shortcut type which would be convenient for adding class variables safely.
typedef CPPPyObjectContainer<s_TSIGContext, TSIGContext> TSIGContextContainer;
54
55
56
57
58
59
60
61
62
63

//
// We declare the functions here, the definitions are below
// the type definition of the object, since both can use the other
//

// General creation and destruction
int TSIGContext_init(s_TSIGContext* self, PyObject* args);
void TSIGContext_destroy(s_TSIGContext* self);

64
65
66
67
68
// Class specific methods
PyObject* TSIGContext_getState(s_TSIGContext* self);
PyObject* TSIGContext_getError(s_TSIGContext* self);
PyObject* TSIGContext_sign(s_TSIGContext* self, PyObject* args);
PyObject* TSIGContext_verify(s_TSIGContext* self, PyObject* args);
69
PyObject* TSIGContext_lastHadSignature(s_TSIGContext* self);
70

71
72
73
74
75
76
77
78
79
80
// These are the functions we export
// For a minimal support, we don't need them.

// This list contains the actual set of functions we have in
// python. Each entry has
// 1. Python method name
// 2. Our static function here
// 3. Argument type
// 4. Documentation
PyMethodDef TSIGContext_methods[] = {
81
82
83
84
85
86
87
88
89
90
91
92
    { "get_state", reinterpret_cast<PyCFunction>(TSIGContext_getState),
      METH_NOARGS,
      "Return the current state of the context (mainly for tests)" },
    { "get_error", reinterpret_cast<PyCFunction>(TSIGContext_getError),
      METH_NOARGS,
      "Return the TSIG error as a result of the latest verification" },
    { "sign",
      reinterpret_cast<PyCFunction>(TSIGContext_sign), METH_VARARGS,
      "Sign a DNS message." },
    { "verify",
      reinterpret_cast<PyCFunction>(TSIGContext_verify), METH_VARARGS,
      "Verify a DNS message." },
93
94
    { "last_had_signature",
      reinterpret_cast<PyCFunction>(TSIGContext_lastHadSignature), METH_NOARGS,
Jelte Jansen's avatar
Jelte Jansen committed
95
      "Return True if the last verified message contained a signature" },
96
97
98
    { NULL, NULL, 0, NULL }
};

99
100
101
102
int
TSIGContext_init(s_TSIGContext* self, PyObject* args) {
    try {
        // "From key" constructor
103
        const PyObject* tsigkey_obj;
104
        if (PyArg_ParseTuple(args, "O!", &tsigkey_type, &tsigkey_obj)) {
105
            self->cppobj = new TSIGContext(PyTSIGKey_ToTSIGKey(tsigkey_obj));
106
107
108
109
110
            return (0);
        }

        // "From key param + keyring" constructor
        PyErr_Clear();
111
112
113
        const PyObject* keyname_obj;
        const PyObject* algname_obj;
        const PyObject* keyring_obj;
114
115
116
        if (PyArg_ParseTuple(args, "O!O!O!", &name_type, &keyname_obj,
                             &name_type, &algname_obj, &tsigkeyring_type,
                             &keyring_obj)) {
117
118
119
            self->cppobj = new TSIGContext(PyName_ToName(keyname_obj),
                                           PyName_ToName(algname_obj),
                                           PyTSIGKeyRing_ToTSIGKeyRing(keyring_obj));
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
            return (0);
        }
    } catch (const exception& ex) {
        const string ex_what = "Failed to construct TSIGContext object: " +
            string(ex.what());
        PyErr_SetString(po_IscException, ex_what.c_str());
        return (-1);
    } catch (...) {
        PyErr_SetString(po_IscException,
                        "Unexpected exception in constructing TSIGContext");
        return (-1);
    }

    PyErr_SetString(PyExc_TypeError,
                    "Invalid arguments to TSIGContext constructor");

    return (-1);
}

void
TSIGContext_destroy(s_TSIGContext* const self) {
    delete self->cppobj;
    self->cppobj = NULL;
    Py_TYPE(self)->tp_free(self);
}

PyObject*
TSIGContext_getState(s_TSIGContext* self) {
    return (Py_BuildValue("I", self->cppobj->getState()));
}

PyObject*
TSIGContext_getError(s_TSIGContext* self) {
    try {
        PyObjectContainer container(createTSIGErrorObject(
155
                                    self->cppobj->getError()));
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
        return (Py_BuildValue("O", container.get()));
    } catch (const exception& ex) {
        const string ex_what =
            "Unexpectedly failed to get TSIGContext error: " +
            string(ex.what());
        PyErr_SetString(po_IscException, ex_what.c_str());
    } catch (...) {
        PyErr_SetString(po_IscException,
                        "Unexpected exception in TSIGContext.get_error");
    }
    return (NULL);
}

PyObject*
TSIGContext_sign(s_TSIGContext* self, PyObject* args) {
    long qid = 0;
    const char* mac;
    Py_ssize_t mac_size;

    if (PyArg_ParseTuple(args, "ly#", &qid, &mac, &mac_size)) {
        if (qid < 0 || qid > 0xffff) {
            PyErr_SetString(PyExc_ValueError,
                            "TSIGContext.sign: QID out of range");
            return (NULL);
        }

        try {
            ConstTSIGRecordPtr record = self->cppobj->sign(qid, mac, mac_size);
            return (createTSIGRecordObject(*record));
        } catch (const TSIGContextError& ex) {
            PyErr_SetString(po_TSIGContextError, ex.what());
        } catch (const exception& ex) {
            const string ex_what = "Unexpected failure in TSIG sign: " +
                string(ex.what());
            PyErr_SetString(po_IscException, ex_what.c_str());
        } catch (...) {
            PyErr_SetString(PyExc_SystemError,
                            "Unexpected failure in TSIG sign");
        }
    } else {
        PyErr_SetString(PyExc_TypeError,
                        "Invalid arguments to TSIGContext.sign");
    }

    return (NULL);
}

PyObject*
TSIGContext_verify(s_TSIGContext* self, PyObject* args) {
    const char* data;
    Py_ssize_t data_len;
207
    PyObject* py_record;
208
    PyObject* py_maybe_none;
209
    const TSIGRecord* record;
210
211
212

    if (PyArg_ParseTuple(args, "O!y#", &tsigrecord_type, &py_record,
                         &data, &data_len)) {
213
        record = &PyTSIGRecord_ToTSIGRecord(py_record);
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
    } else if (PyArg_ParseTuple(args, "Oy#", &py_maybe_none, &data,
                                &data_len)) {
        record = NULL;
    } else {
        PyErr_SetString(PyExc_TypeError,
                        "Invalid arguments to TSIGContext.verify");
        return (NULL);
    }
    PyErr_Clear();

    try {
        const TSIGError error = self->cppobj->verify(record, data, data_len);
        return (createTSIGErrorObject(error));
    } catch (const TSIGContextError& ex) {
        PyErr_SetString(po_TSIGContextError, ex.what());
    } catch (const InvalidParameter& ex) {
        PyErr_SetString(po_InvalidParameter, ex.what());
    } catch (const exception& ex) {
        const string ex_what = "Unexpected failure in TSIG verify: " +
            string(ex.what());
        PyErr_SetString(po_IscException, ex_what.c_str());
    } catch (...) {
        PyErr_SetString(PyExc_SystemError, "Unexpected failure in TSIG verify");
    }

    return (NULL);
}
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260

PyObject*
TSIGContext_lastHadSignature(s_TSIGContext* self) {
    try {
        long result = self->cppobj->lastHadSignature();
        return (PyBool_FromLong(result));
    } catch (const TSIGContextError& ex) {
        PyErr_SetString(po_TSIGContextError, ex.what());
    } catch (const exception& ex) {
        const string ex_what =
            "Unexpected failure in TSIG lastHadSignature: " +
            string(ex.what());
        PyErr_SetString(po_IscException, ex_what.c_str());
    } catch (...) {
        PyErr_SetString(PyExc_SystemError,
                        "Unexpected failure in TSIG lastHadSignature");
    }

    return (NULL);
}
261
262
263
264
265
266
267
268
} // end of unnamed namespace

namespace isc {
namespace dns {
namespace python {
// Definition of class specific exception(s)
PyObject* po_TSIGContextError;

269
// This defines the complete type for reflection in python and
270
// parsing of PyObject* to s_TSIGContext
271
// Most of the functions are not actually implemented and NULL here.
272
PyTypeObject tsigcontext_type = {
273
    PyVarObject_HEAD_INIT(NULL, 0)
274
    "pydnspp.TSIGContext",
275
    sizeof(s_TSIGContext),                 // tp_basicsize
276
    0,                                  // tp_itemsize
277
    reinterpret_cast<destructor>(TSIGContext_destroy),       // tp_dealloc
278
279
280
281
282
283
284
285
    NULL,                               // tp_print
    NULL,                               // tp_getattr
    NULL,                               // tp_setattr
    NULL,                               // tp_reserved
    NULL,                               // tp_repr
    NULL,                               // tp_as_number
    NULL,                               // tp_as_sequence
    NULL,                               // tp_as_mapping
286
    NULL,                               // tp_hash
287
288
289
290
291
    NULL,                               // tp_call
    NULL,                               // tp_str
    NULL,                               // tp_getattro
    NULL,                               // tp_setattro
    NULL,                               // tp_as_buffer
292
293
294
295
296
297
298
299

    // We allow the python version of TSIGContext to act as a base class.
    // From pure design point of view, this is wrong because it's not intended
    // to be inherited.  However, cryptographic operations are generally
    // difficult to test, so it would be very advantageous if we can define
    // a mock context class.
    Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, // tp_flags

300
    "The TSIGContext class objects is...(COMPLETE THIS)",
301
302
    NULL,                               // tp_traverse
    NULL,                               // tp_clear
303
    NULL, // tp_richcompare
304
305
306
    0,                                  // tp_weaklistoffset
    NULL,                               // tp_iter
    NULL,                               // tp_iternext
307
    TSIGContext_methods,                   // tp_methods
308
309
310
311
312
313
314
    NULL,                               // tp_members
    NULL,                               // tp_getset
    NULL,                               // tp_base
    NULL,                               // tp_dict
    NULL,                               // tp_descr_get
    NULL,                               // tp_descr_set
    0,                                  // tp_dictoffset
315
    reinterpret_cast<initproc>(TSIGContext_init),            // tp_init
316
317
318
319
320
321
322
323
324
325
326
327
328
    NULL,                               // tp_alloc
    PyType_GenericNew,                  // tp_new
    NULL,                               // tp_free
    NULL,                               // tp_is_gc
    NULL,                               // tp_bases
    NULL,                               // tp_mro
    NULL,                               // tp_cache
    NULL,                               // tp_subclasses
    NULL,                               // tp_weaklist
    NULL,                               // tp_del
    0                                   // tp_version_tag
};

329
330
bool
PyTSIGContext_Check(PyObject* obj) {
331
332
333
    if (obj == NULL) {
        isc_throw(PyCPPWrapperException, "obj argument NULL in typecheck");
    }
334
335
336
337
338
    return (PyObject_TypeCheck(obj, &tsigcontext_type));
}

TSIGContext&
PyTSIGContext_ToTSIGContext(PyObject* tsigcontext_obj) {
339
340
341
342
    if (tsigcontext_obj == NULL) {
        isc_throw(PyCPPWrapperException,
                  "obj argument NULL in TSIGContext PyObject conversion");
    }
343
344
345
346
    s_TSIGContext* tsigcontext = static_cast<s_TSIGContext*>(tsigcontext_obj);
    return (*tsigcontext->cppobj);
}

347
348
349
} // namespace python
} // namespace dns
} // namespace isc