Statistics
| Branch: | Tag: | Revision:

root / snf-cyclades-app / synnefo / userdata / models.py @ 19b2c29d

History | View | Annotate | Download (4.2 kB)

1
#
2
# Copyright 2011 GRNET S.A. All rights reserved.
3
#
4
# Redistribution and use in source and binary forms, with or
5
# without modification, are permitted provided that the following
6
# conditions are met:
7
#
8
#   1. Redistributions of source code must retain the above
9
#      copyright notice, this list of conditions and the following
10
#      disclaimer.
11
#
12
#   2. Redistributions in binary form must reproduce the above
13
#      copyright notice, this list of conditions and the following
14
#      disclaimer in the documentation and/or other materials
15
#      provided with the distribution.
16
#
17
# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
18
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
19
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
20
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
21
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
24
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
25
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
27
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
28
# POSSIBILITY OF SUCH DAMAGE.
29
#
30
# The views and conclusions contained in the software and
31
# documentation are those of the authors and should not be
32
# interpreted as representing official policies, either expressed
33
# or implied, of GRNET S.A.
34

    
35
import base64
36
import binascii
37
import re
38

    
39
from hashlib import md5
40

    
41
from django.db import models
42
from django.conf import settings
43
from django.core.exceptions import ValidationError, NON_FIELD_ERRORS
44
from django.core.validators import MaxLengthValidator
45
from django.db.models.signals import pre_save
46

    
47
try:
48
    from paramiko import rsakey, dsskey, SSHException
49
except:
50
    pass
51

    
52
SSH_KEY_MAX_CONTENT_LENGTH = getattr(settings,
53
                                     'USERDATA_SSH_KEY_MAX_CONTENT_LENGTH',
54
                                     30000)
55

    
56

    
57
class ProfileModel(models.Model):
58
    """
59
    Abstract model, provides a basic interface for models that store
60
    user specific information
61
    """
62

    
63
    user = models.CharField(max_length=100)
64

    
65
    class Meta:
66
        abstract = True
67
        app_label = 'userdata'
68

    
69

    
70
class PublicKeyPair(ProfileModel):
71
    """
72
    Public key model
73
    """
74
    name = models.CharField(max_length=255, null=False, blank=False)
75
    content = models.TextField(validators=[
76
        MaxLengthValidator(SSH_KEY_MAX_CONTENT_LENGTH)])
77
    fingerprint = models.CharField(max_length=100, null=False, blank=True)
78

    
79
    class Meta:
80
        app_label = 'userdata'
81

    
82
    def full_clean(self, *args, **kwargs):
83
        # update fingerprint before clean
84
        self.update_fingerprint()
85
        super(PublicKeyPair, self).full_clean(*args, **kwargs)
86

    
87
    def key_data(self):
88
        return self.content.split(" ", 1)
89

    
90
    def get_key_object(self):
91
        """
92
        Identify key contents and return appropriate paramiko public key object
93
        """
94
        key_type, data = self.key_data()
95
        data = base64.b64decode(data)
96

    
97
        if key_type == "ssh-rsa":
98
            key = rsakey.RSAKey(data=data)
99
        elif key_type == "ssh-dss":
100
            key = dsskey.DSSKey(data=data)
101
        else:
102
            raise Exception("Invalid key type")
103

    
104
        return key
105

    
106
    def clean_key(self):
107
        key = None
108
        try:
109
            key = self.get_key_object()
110
        except:
111
            raise ValidationError("Invalid SSH key")
112

    
113
    def clean(self):
114
        if PublicKeyPair.user_limit_exceeded(self.user):
115
            raise ValidationError("SSH keys limit exceeded.")
116

    
117
    def update_fingerprint(self):
118
        try:
119
            fp = binascii.hexlify(self.get_key_object().get_fingerprint())
120
            self.fingerprint = ":".join(re.findall(r"..", fp))
121
        except:
122
            self.fingerprint = "unknown fingerprint"
123

    
124
    def save(self, *args, **kwargs):
125
        self.update_fingerprint()
126
        super(PublicKeyPair, self).save(*args, **kwargs)
127

    
128
    @classmethod
129
    def user_limit_exceeded(cls, user):
130
        return (PublicKeyPair.objects.filter(user=user).count() >=
131
                settings.USERDATA_MAX_SSH_KEYS_PER_USER)