Statistics
| Branch: | Tag: | Revision:

root / ui / userdata / models.py @ 49f50673

History | View | Annotate | Download (4 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 md5
38
import re
39

    
40
from django.db import models
41
from django.conf import settings
42
from django.core.exceptions import ValidationError, NON_FIELD_ERRORS
43

    
44
from django.db.models.signals import pre_save
45

    
46
from synnefo.db import models as synnefo_models
47

    
48
User = synnefo_models.SynnefoUser
49

    
50
try:
51
    from paramiko import rsakey, dsskey, SSHException
52
except:
53
    pass
54

    
55

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

    
62
    user = models.ForeignKey(User)
63

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

    
68

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

    
77
    class Meta:
78
        app_label = 'userdata'
79

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

    
85
    def key_data(self):
86
        return self.content.split(" ", 1)
87

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

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

    
102
        return key
103

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

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

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

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

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